Change color of canvas element - javascript

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)

Related

How to remove only one path from a canvas element

I want to either remove, change the colour of or change the position of the second line.
Also, is there a way to make the colour of an already created line different?
var cvs = document.querySelector('#canvas')
var ctx = cvs.getContext('2d')
cvs.height = window.innerHeight - 40
cvs.width = window.innerWidth - 40
window.addEventListener('resize', () => {
cvs.height = window.innerHeight - 40;
cvs.width = window.innerWidth - 40;
})
ctx.beginPath();
ctx.strokeStyle = 'red'
ctx.lineWidth = '5'
ctx.lineCap = 'round'
ctx.moveTo(200, 600)
ctx.lineto(100,100)
ctx.closePath();
//Second path which is what i want to remove only
ctx.beginPath();
ctx.strokeStyle = 'blue'
ctx.lineWidth = '37px'
ctx.moveTo(100,100)
ctx.lineTo(300, 500)
ctx.stroke()
ctx.closePath()
Objects painted on the canvas cannot be modified, but they can be painted over. Unlike HTML or SVG, the the canvas does not have its own DOM, so there is no way to access objects that have already painted on the canvas.
Approach 1:
The most common approach is to clear the canvas, adjust any attributes (position, color, etc), and repaint the objects onto the canvas.
ctx.clearRect(0, 0, cvs.width, cvs.height) //removes everything from the canvas
ctx.beginPath();
ctx.strokeStyle = 'red'
ctx.lineWidth = '5'
ctx.lineCap = 'round'
ctx.moveTo(200, 600)
ctx.lineTo(100,100)
ctx.stroke();
ctx.closePath(); //repaints the first object, the second path is gone.
Pros:
more robust: will work in all situations (even when objects overlap)
Scales well: better when lots of objects are painted
Cons:
every object has to be repainted on the canvas. (removes everything)
Approach 2:
The closest approach to removing a single object, it paints over the existing object and repaint it somewhere else.
ctx.beginPath();
ctx.strokeStyle = 'white' //background color
ctx.lineWidth = '37px'
ctx.moveTo(100,100);
ctx.lineTo(300, 500);
ctx.stroke();
ctx.closePath(); // covers up the second path
ctx.beginPath();
ctx.strokeStyle = 'blue'
ctx.lineWidth = '37px'
ctx.moveTo(100,100)
ctx.lineTo(600, 500) //repaint this object somewhere else
ctx.stroke()
ctx.closePath()
Pros:
Only removes the second path, leaves everything else
simpler when fewer objects are on the canvas
Cons:
Will not work when objects overlap.
Does not scale well: this solution will get more complex when more objects are being modified.
More resources:
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial

How to prevent a path from being filled (again)?

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

How to draw a trigonometric pattern on HTML canvas?

I'm trying to draw a graphic pattern of lines from the black to the red depending on the Y value of a wave. To find out if I'm doing it right whit the approach, I started a test in JSFiddle:
Test
var j,k;
k=255;
var green=150;
var blue=150;
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
for(j=0;j<k;j++)
{
ctx.beginPath();
ctx.moveTo(j, 0);
ctx.lineTo(j, 150);
ctx.strokeStyle = "rgb("&j&", 0, 0)";
ctx.stroke();
}
But the result is just a grey tone in all the lines, although the drawing method is inside a loop and the 'red' value is changing.
Putting #Juhana's good suggestion into practice:
var j,k;
k=255;
var green=150;
var blue=150;
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
for(j=0;j<k;j++){
ctx.beginPath();
ctx.moveTo(j, 0);
ctx.lineTo(j, 150);
ctx.strokeStyle = "rgb("+j+",0,0)";
ctx.stroke();
}

Javascript canvas: animate box on touch, view only borders

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.

HTML5 Canvas - How to fill() a specific context

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/

Categories