0

So I did some research on canvas rotation, and came across a great method of rotating individual objects.(Source) I was in the middle of understanding how the code worked when, as I was rewriting the code, came across this strange thing.

Here's the JSFiddle from the link:

var canvas = document.getElementById('test_canvas');
var ctx = canvas.getContext('2d');

var buffer = document.createElement('canvas');
buffer.width = buffer.height = 60;
var bctx = buffer.getContext('2d');
bctx.translate(30, 30);
bctx.rotate(0.5);
bctx.fillStyle = 'rgb(255, 0, 0)';
bctx.fillRect(-15, -15, 30, 30);

ctx.fillStyle = 'rgb(0, 255, 0)';
ctx.fillRect(30, 30, 30, 30);
ctx.drawImage(buffer, 50, 50);

and here's my JSFiddle:

var myCanvas = document.getElementById("buffer");
var context = myCanvas.getContext('2d');

var myCanvas1 = document.createElement('canvas');
myCanvas1.width = myCanvas1.height = 60;
var newContext = myCanvas1.getContext('2d');
newContext.translate(30, 30);
newContext.rotate(0.5);
newContext.fillStyle = 'rgb(255, 0, 0)';
newContext.fillRect(-15, -15, 30, 30);

context.fillStyle = 'rgb(0, 255, 0)';
context.fillRect(30, 30, 30, 30);
context.drawImage(buffer, 50, 50);

They are nearly exact copies of one another except my code doesn't rotate the object. I've been looking at this code for a few hours baffled, and I'd really like to be told what the other guy did right.

Community
  • 1
  • 1
jatmdm
  • 75
  • 1
  • 1
  • 5

1 Answers1

0

Your problem is with this line:

context.drawImage(buffer, 50, 50);

The original code used a variable called buffer and assigned a new canvas element to it:

var buffer = document.createElement('canvas');

You've named yours:

var myCanvas1 = document.createElement('canvas');

but later on are drawing your image into a non-existent variable buffer

dc5
  • 12,341
  • 2
  • 35
  • 47