Reputation: 4149
I draw varicolored canvas and on click redraw it and draw black rectangles. But rectangles does not remove! What I'm doing wrong? Demo: http://jsfiddle.net/82nnJ/
function draw_palette() {
$c = document.getElementById('palette');
$ctx = $c.getContext('2d');
var size = 256;
$ctx.clearRect(0, 0, size, size); //
var r = 255;
var a = 255;
for (var g = 0; g < size; g++) {
for (var b = 0; b < size; b++) {
$ctx.fillStyle = "rgba(" + r + ", " + g + ", " + b + ", " + (a/255) + ")";
$ctx.fillRect(g, b, 1, 1);
}
}
}
jQuery(document).ready(function() {
draw_palette();
$('#palette').click(function(e) {
draw_palette();
var x = e.pageX - $(this).position().left;
var y = e.pageY - $(this).position().top;
var radius = 5;
$ctx.rect(x-radius, y-radius, 2*radius+1, 2*radius+1);
$ctx.strokeStyle = 'black';
$ctx.stroke();
});
});
Upvotes: 0
Views: 114
Reputation: 1
I just solved a similar issue. I have a chart that was programmed in javascript on the web-side and a server transmitting data to the chart. Used websockets to update the chart on a realtime basis.
Basically in the onmessage event the Canvas object was destroyed and constructed using the DOM. With the previous object destroyed this ensures that it repaints correctly.
Here's what I did...
var c = document.getElementsByName("myCanvas")[0];
if (c != null)
{
c.remove();
}
var c = document.createElement("canvas");
c.setAttribute("name", "myCanvas");
c.setAttribute("width", 900);
c.setAttribute("height", 600);
c.setAttribute("style", "border:1px solid #d3d3d3");
var ctx = c.getContext("2d");
document.body.append(c);
Upvotes: 0
Reputation: 4149
There should be beginPath and closePath methods.
$ctx.beginPath();
$ctx.rect(x-radius, y-radius, 2*radius+1, 2*radius+1);
$ctx.strokeStyle = 'black';
$ctx.stroke();
$ctx.closePath();
Upvotes: 1