I'm trying to make a website where an image is drawn on Canvas, then later the user is able to press a button to ctx.fill() certain parts of it with color. I'm running into issues where I can only ctx.fill() the most recently created shape which often isn't the shape I want.
Here's an example. In this code (live at http://build.rivingtondesignhouse.com/piol/test/) I'm trying to draw the first rectangle, then save() it on the stack, then draw the second rectangle (and don't save it), then when my fill() function is called I want to restore() the first rectangle and ctx.fill() it with a different pattern. It doesn't work!
In practice, I'm actually trying to fill the gray part of this complex shape with any color the user chooses AFTER the image has been drawn, but I think the technique is the same. (http://build.rivingtondesignhouse.com/piol/test/justTop.html)
Thanks in advance for any help!!!
Here's the code:
<script type="text/javascript">
var canvas;
var ctx;
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
draw();
}
function draw() {
ctx.fillStyle = '#FA6900';
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.shadowBlur = 4;
ctx.shadowColor = 'rgba(204, 204, 204, 0.5)';
ctx.fillRect(0,0,15,150);
ctx.save();
ctx.fillStyle = '#E0E4CD';
ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;
ctx.shadowBlur = 4;
ctx.shadowColor = 'rgba(204, 204, 204, 0.5)';
ctx.fillRect(30,0,30,150);
}
function fill(){
var image = new Image();
image.src = "http://www.html5canvastutorials.com/demos/assets/wood-pattern.png";
image.onload = drawPattern;
function drawPattern() {
ctx.restore();
ctx.fillStyle = ctx.createPattern(image, "repeat");
ctx.fill();
}
}
init();
There are a few misunderstands that we need to clear up before I can answer the question.
save() and restore() do not save and restore the canvas bitmap. Instead they save and restore all properties that are set on the canvas context and that's all!
For example
ctx.fillStyle = 'red';
ctx.save(); // save the fact that the fillstyle is red
ctx.fillStyle = 'blue'; // change the fillstyle
ctx.fillRect(0,0,5,5); // draws a blue rectangle
ctx.restore(); // restores the old context state, so the fillStyle is back to red
ctx.fillRect(10,0,5,5); // draws a red rectangle // draws a red rectangle
See that code live here.
So you aren't saving a rectangle (or anything drawn) by calling save(). The only way you you can save the bitmap is by drawing it (or part of it) to another canvas (using anotherCanvasContext.drawImage(canvasIWantToSave, 0, 0)) or by saving enough information that you can redraw the entire scene with the appropriate changes.
Here is an example of one way you could re-structure your code so that it does what you want: http://jsfiddle.net/xwqXb/
Related
I was working against a financial library that requires me to provide realtime updates to a line chart in canvas. To optimize the process of updating the chart, I thought of just updated the latest data-point rather than clearing and re-drawing the entire canvas.
When re-rendering only the latest datapoint frequently, I'm noticing that the line is not clear(there's a spot in the image).
Here's how the line looks initially(no redraw)
And after a few updates of calling "partial_rerender", this is how the line looks:
Notice the "joining" of the 2 lines is visible with a darker shade.
Is there a way to achieve partial re-drawing of lines only for the latest data point & not drawing the entire line completely?
Reference code
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.lineWidth = 2;
ctx.lineJoin = "miter";
ctx.moveTo(20, 50);
ctx.lineTo(100, 50);
ctx.save();
ctx.lineTo(150, 60);
ctx.stroke();
/*Call this every second to re-draw only the latest data point*/
function partial_rerender(){
ctx.clearRect(100,50, 400,400);
ctx.restore();
ctx.lineTo(150, 60);
ctx.stroke();
}
You need to create a new path each time you render or you end up re- rendering the same content over and over.
ctx.save() and ctx.restore() push and pop from a stack, for every restore you need to have a matching save. ctx.save(), ctx.restore(), ctx.restore()the second restore does nothing as there is no matching save.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.lineWidth = 2;
ctx.lineJoin = "miter";
ctx.moveTo(20, 50);
ctx.lineTo(100, 50);
ctx.save();
ctx.lineTo(150, 60);
ctx.stroke();
// Your function should look more like this
function partial_rerender(){
ctx.lineWidth = 2;
ctx.lineJoin = "miter";
ctx.save(); // needed to remove clip
ctx.beginPath(); // removes old path ready to create a new one
ctx.rect(100,50, 400,400); // create a clip area
ctx.clip(); // activate the clip area
ctx.clearRect(100,50, 400,400);
ctx.beginPath(); // needed to draw the new path
ctx.moveTo(100,50)
ctx.lineTo(150, 60);
ctx.stroke();
ctx.restore(); // remove the clip area
}
When you draw onto the canvas you do override the necessary pixels. But the rest stays the same.
What you are trying to achieve is not possible. You have to clear the canvas (canvas.clear()) and then redraw all elements to remove these artifacts from previous draw calls and to achieve your desired result.
I'm trying to use globalCompositeOperation on an object within a <canvas> element but my goal is to blend with an object outside of the canvas - a plain html markup element like a paragraph.
My end goal will be inverting the content on the page using difference like so
My existing code is below. Is this even possible?
var canvas = document.getElementById('canvas');
window.onresize=function(){
"use strict";
var winMin = Math.min(window.innerWidth,window.innerHeight);
canvas.width = winMin;
canvas.height = winMin;
var w = winMin / 3;
var ctx = canvas.getContext('2d');
ctx.globalCompositeOperation = 'multiply';
ctx.globalAlpha = .5;
//magenta
ctx.fillStyle = 'rgb(255,0,255)';
ctx.beginPath();
ctx.arc(w, w, w, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
//cyan
ctx.fillStyle = 'rgb(0,255,255)';
ctx.beginPath();
ctx.arc(w*2, w, w, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
};
window.onresize();
Codepen: http://codepen.io/jeremypbeasley/pen/NqwGoO
The globalCompositeOperation blending operations define how pixels backed by the canvas element blend with fragments to be written to that backing. That has nothing to do with pixels that live in some other dimension of the web page, like the DOM. Total rasterization of the canvas occurs and some other graphics system composites the pixels of the canvas onto the pixels of the rest of the web page. Reflow of the web page could happen at any time, but that does not mean that the canvas would be re-rasterized, just re-composited, in which case the globalCompositeOperations would have no effect and you wouldn't see the photo negative effect you desire.
I am drawing some shapes on a canvas element. The first element is a path, which should not get filled at all. I know I can set fillStyle to none, but it gets filled twice.
Here is some example code (also on jsfiddle):
can = document.getElementById('can');
ctx = can.getContext('2d');
function drawPoint(x,y){
ctx.arc(x,y,12,0,Math.PI*2,false);
ctx.fillStyle ='rgba(255, 0, 0, 0.2)';
ctx.fill();
}
function shape(){
ctx.fillStyle = 'rgba(0,255,0,0.2)';
ctx.beginPath();
ctx.moveTo(10,10);
ctx.lineTo(100,30);
ctx.lineTo(30,200)
ctx.closePath();
ctx.stroke();
ctx.fill();
}
shape();
drawPoint(30,12);
This is just an example code, to illustrate the problem I am facing.
When I draw the shape afterwards, the point is in the background. So this won't work. I also searched for resources on how the fill method works but couldn't find anything useful.
So how can I draw the shape without filling it?
Just don't call fill()...
For example, if you want your method reusable you can use a flag:
function shape(fill){
fill = fill || false;
ctx.fillStyle = 'rgba(0,255,0,0.2)';
ctx.beginPath();
ctx.moveTo(10,10);
ctx.lineTo(100,30);
ctx.lineTo(30,200)
ctx.closePath();
ctx.stroke();
if (fill) ctx.fill();
}
Now you can call:
draw(); /// won't fill
draw(true); /// fills
Also add a beginPath() to this method or else it will just add to the path of the first shape (which perhaps is what you mean?):
function drawPoint(x,y){
ctx.beginPath();
ctx.arc(x,y,12,0,Math.PI*2,false);
ctx.fillStyle ='rgba(255, 0, 0, 0.2)';
ctx.fill();
}
Hope this helps (and that I didn't misunderstand your question)!
Modified fiddle here
I am trying to do a simple animation with html5. Please take a look at the link below, through a touch screen device.
https://dl.dropbox.com/u/41627/wipe.html
The problem is as follows : Every time the user touches the screen , a box gets drawn around his finger which animates from small to big. I want just the outer most boundary to be visible and not the rest. I do not want to clear the canvas as I want the state of the rest of the canvas to be preserved.
Images to illustrate the issue:
My code is as follows :
function init() {
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');
img.onload = function () {
ctx.beginPath();
ctx.drawImage(img, 0, 0);
ctx.closePath();
ctx.globalCompositeOperation = 'destination-out';
}
img.src = "https://dl.dropbox.com/u/41627/6.jpg";
function drawPoint(pointX,pointY){
var grd = ctx.createRadialGradient(pointX, pointY, 0, pointX, pointY, 30);
grd.addColorStop(0, "rgba(255,255,255,.6)");
grd.addColorStop(1, "transparent");
ctx.fillStyle = grd;
ctx.beginPath();
ctx.arc(pointX,pointY,50,0,Math.PI*2,true);
ctx.fill();
ctx.closePath();
}
var a = 0;
var b = 0;
function boxAround(pointX,pointY, a, b) {
ctx.globalCompositeOperation = 'source-over';
ctx.strokeStyle = "black";
ctx.strokeRect(pointX-a, pointY-b, (2*a), (2*b));
ctx.globalCompositeOperation = 'destination-out';
if(a < 100) {
setTimeout(function() {
boxAround(pointX,pointY, a+5, b+5);
}, 20);
}
}
canvas.addEventListener('touchstart',function(e){
drawPoint(e.touches[0].screenX,e.touches[0].screenY);
boxAround(e.touches[0].screenX,e.touches[0].screenY,0 , 0);
},false);
canvas.addEventListener('touchmove',function(e){
e.preventDefault();
drawPoint(e.touches[0].screenX,e.touches[0].screenY);
},false);
You can achieve this effect by either using a second canvas, or even just having the box be a plain <div> element that is positioned over the canvas. Otherwise, there is no way around redrawing your canvas.
I am trying to change the color of line drawn on canvas dynamically...
ctx.moveTo(0, 0);
ctx.lineTo(0, 200);
ctx.strokeStyle = "Grey"
It could be mouseover event or press botton or mouse click event, I want to change the color of line or make it bold. Is it possible to change the color by adding event or is it possible to give style on an event on particular element?
Very close. In a sense, you can't really "change" the color of an element on the canvas because it has no scene graph, or, in other words, it has no history of what has been drawn on the canvas. To change the color of a line, you would have to redraw the line.
ctx.moveTo(0, 0);
ctx.lineTo(0, 200);
ctx.strokeStyle = "Grey";
ctx.stroke();
// To make the line bold and red
ctx.moveTo(0, 0);
ctx.lineTo(0, 200);
ctx.strokeStyle = "Red";
ctx.lineWidth = 5;
ctx.stroke();
If the canvas had a more complex scene going on, you would have to redraw the entire scene. There are numerous Javascript libraries that extend the base features of the canvas tag, and provide other drawing capabilities. You may want to take a look at Processing, it looks quite impressive.
I was having the same problem, I did it by moving another line with another color of different canvas element, so it gives appearance of line changing its color dynamically.
function drawGreyLine() {
ctx1.clearRect(0, 0, WIDTH, HEIGHT);
ctx1.strokeStyle = "Grey"; // line color
ctx1.moveTo(0, 0);
ctx1.moveTo(0, 200);
ctx1.lineTo(200, 200);
}
function drawColorLine() {
x += dx;
if (x <= 200) {
ctx2.beginPath();
ctx2.lineWidth = 5;
ctx2.lineCap = "round";
ctx2.strokeStyle = "sienna"; // line color
ctx2.moveTo(0, 200);
ctx2.lineTo(x, 200);
ctx2.moveTo(200, 200);
ctx2.stroke();
}
}
Hope this solves your problem.... :)
var canvas = document.getElementById('canvas');
var ctx=canvas.getContext('2d');
var line1={x:10,y:10, l:40, h:1}
var down=false;
var mouse={x:0,y:0}
canvas.onmousemove=function(e){ mouse={x:e.pageX-this.offsetLeft,y:e.pageY-this.offsetTop};
this.onmousedown=function(){down=true};
this.onmouseup=function(){down=false} ;
}
setInterval(function(){
ctx.clearRect(0,0,canvas.width,canvas.height)
ctx.beginPath()
ctx.moveTo(line1.x,line1.y)
ctx.lineTo(line1.x +line1.l,line1.y)
ctx.lineTo(line1.x +line1.l,line1.y+line1.h)
ctx.lineTo(line1.x,line1.y+line1.h)
ctx.isPointInPath(mouse.x,mouse.y)? (ctx.fillStyle ="red",line1.x=down?mouse.x:line1.x,line1.y=down?mouse.y:line1.y):(ctx.fillStyle ="blue")
ctx.fill()
},100)