tags:

views:

849

answers:

1

Hi, I have 2 canvas created on the same canvas. Is it possible to drag the small black one around? I want to make it draggable but I can not find any online tutorial or demo on this. Is it possible? I had looked to Canvas moveTo or transitions but I was unable to make it work.

The code is here http://jsfiddle.net/35P9F/2/

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

  var radgrad3 = ctx.createLinearGradient(255,10,0,180,80,190);
  radgrad3.addColorStop(0, '#00C9FF');
  radgrad3.addColorStop(1, 'red');

  ctx.fillStyle = radgrad3;
  ctx.fillRect(0,0,255,255);



  var ctx4 = document.getElementById('canvas').getContext('2d');
  var radgrad4 = ctx4.createLinearGradient(0, 0, 0, 255);
  radgrad4.addColorStop(0, '#000000');
  radgrad4.addColorStop(1, '#ff0000');

  ctx4.fillStyle = radgrad4;
  ctx4.fillRect(0,0,25,25);

Thank you.

+3  A: 

Short answer: there's no automatic way to do so.

Long answer: <canvas> uses "immediate mode" drawing, which means that it doesn't remember what you've done before. If you give it a command, it immediately renders it into pixels on the screen, and then forgets about it. If you want something on the screen to act like it's responding to the mouse, you have to track the mouse yourself and redraw the entire screen for every frame, putting the black square in a different position each time.

What you may want instead is a "retained mode" graphics element, which means that it remembers what you've done and only turns things into pixels at the last moment. SVG is an excellent example of this. When you draw something in SVG, you create actual elements just like in HTML, and can change their attributes to make them move or change without having to recreate the entire scene every time.

Xanthir