I was surprised to find out that apparently the canvas API does not allow you to apply gradients to shadows like this:
var grad = ctx.createLinearGradient(fromX, fromY, toX, toY);
grad.addColorStop(0, "red");
grad.addColorStop(1, "blue");
ctx.strokeStyle = grad;
ctx.lineWidth = 3;
ctx.shadowBlur = 10;
ctx.shadowColor = grad; // doesn't seem to work
ctx.beginPath();
ctx.moveTo(fromX, fromY);
ctx.lineTo(toX, toY);
ctx.closePath();
ctx.stroke();
// linear gradient from start to end of line
var canvas = document.getElementById('mycanvas'),
ctx = canvas.getContext('2d'),
fromX = 3,
fromY = 3,
toX = 197,
toY = 197,
grad = ctx.createLinearGradient(fromX, fromY, toX, toY);
canvas.width = 200;
canvas.height = 200;
grad.addColorStop(0, "red");
grad.addColorStop(1, "blue");
ctx.strokeStyle = grad;
ctx.lineWidth = 3;
ctx.shadowBlur = 20;
ctx.shadowColor = grad;
ctx.beginPath();
ctx.moveTo(fromX, fromY);
ctx.lineTo(toX, toY);
ctx.closePath();
ctx.stroke();
body {
background: black
}
<canvas id="mycanvas"></canvas>
One workaround is to simply draw the line/shape/etc. multiple times at different sizes and opacity to get a similar result:
var grad = ctx.createLinearGradient(fromX, fromY, toX, toY);
canvas.width = 200;
canvas.height = 200;
grad.addColorStop(0, "red");
grad.addColorStop(1, "blue");
ctx.strokeStyle = grad;
ctx.lineWidth = 3;
//ctx.shadowBlur = 20;
//ctx.shadowColor = grad;
for (var i = 10; i > 1; i--) {
ctx.lineWidth = i;
ctx.globalAlpha = 1 / i;
ctx.beginPath();
ctx.moveTo(fromX, fromY);
ctx.lineTo(toX, toY);
ctx.closePath();
ctx.stroke();
}
// linear gradient from start to end of line
var canvas = document.getElementById('mycanvas'),
ctx = canvas.getContext('2d'),
fromX = 3,
fromY = 3,
toX = 197,
toY = 197,
grad = ctx.createLinearGradient(fromX, fromY, toX, toY);
canvas.width = 200;
canvas.height = 200;
grad.addColorStop(0, "red");
grad.addColorStop(1, "blue");
ctx.strokeStyle = grad;
ctx.lineWidth = 3;
//ctx.shadowBlur = 20;
//ctx.shadowColor = grad;
for (var i = 10; i > 1; i--) {
ctx.lineWidth = i;
ctx.globalAlpha = 1 / i;
ctx.beginPath();
ctx.moveTo(fromX, fromY);
ctx.lineTo(toX, toY);
ctx.closePath();
ctx.stroke();
}
body {
background: black;
}
<canvas id="mycanvas"></canvas>
Here's the comparison. Although the change is subtle, the right image shows roughly the desired effect.
Is there a better way of doing this? I imagine there's a more efficient way than drawing the same thing multiple times. Does anyone know of a library that provides this kind of functionality?
Use the filter property of the canvas 2d context. MDN filter though (as usual) it does say filter is not supported on Chrome it has been from some time on the Beta version. For IE I do not know and for FF it has been supported for some time. You will have to test for it if you use it.
UPDATE
Support does not seam to be automatic. Though MDN shows support for Firefox you must set the canvas.filters.enable to true (whatever that means, I am sure firefox lovers know) and seams for chrome you must go to chrome://flags then set experimental canvas features to enabled
More
I have added a fallback as there is such limited support. It uses a second canvas to blur the shadow by using the ctx.imageSmoothingEnabled=true; and rendering at a scale one half the blur amount. So if blur is 5 pixels then in background canvas must be one tenth the size. Then on the original canvas render the background canvas at full size with smoothing on.
No the best result and will no be good for lines, but its fast and can be played around with to optimise results.
Snippet to show how to detect support and use.
var canvas = document.getElementById("canV");
var ctx = canvas.getContext("2d");
var g = ctx.createLinearGradient(10,10,100,100);
for(var i = 0; i <= 1; i+= 0.05){
g.addColorStop(i,"hsl("+Math.floor(i*360)+",100%,50%)");
}
var gDark = ctx.createLinearGradient(20,20,100,100);
for(var i = 0; i <= 1; i+= 0.05){
gDark.addColorStop(i,"hsl("+Math.floor(i*360)+",100%,30%)");
}
ctx.font = "16px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "hanging";
if(ctx.filter !== undefined){
ctx.fillText("Using filter.",65,125);
ctx.fillStyle = gDark;
ctx.filter = "blur(5px)"; // set the blur
ctx.fillRect(20,20,100,100); // draw the shadow
ctx.fillStyle = g; // set the lighter gradoent
ctx.filter = "blur(0px)"; // remove the blur
ctx.lineWidth = 2;
ctx.strokeStyle = "black"
ctx.fillRect(10,10,100,100); // draw the box
ctx.strokeRect(10,10,100,100); // with line to look nice.
}else{
// fallback method
ctx.fillText("Using Fallback.",60,125);
var can = document.createElement("canvas"); // create a second canvas
can.width = Math.floor(canvas.width/10); // size to make one pixel the
can.height =Math.floor(canvas.height/10); // size of the blur
var ctxS = can.getContext("2d");
ctxS.setTransform(1/10,0,0,1/10,0,0); // set scale so can work in same coords
ctxS.fillStyle = gDark;
ctxS.fillRect(20,20,100,100); // draw the shadow
ctx.imageSmoothingEnabled=true;
ctx.drawImage(can,0,0,canvas.width,canvas.height);
}
ctx.fillStyle = g; // set the lighter gradoent
ctx.lineWidth = 2;
ctx.strokeStyle = "black"
ctx.fillRect(10,10,100,100); // draw the box
ctx.strokeRect(10,10,100,100); // with line to look nice.
#canV {
width:200px;
height:200px;
}
<canvas id="canV" width = 200 height =200></canvas>
Related
I am drawing five horizontal lines to an HMTL 5 2D canvas:
var canvas_ctx = my_canvas.getContext("2d");
canvas_ctx.lineWidth = 0.5;
canvas_ctx.strokeStyle = "black";
{
let line_x = 0;
let line_length = canvas_ctx.width;
let offset = 5;
let numLines = 5;
let numYincrement = 10;
for (let i=0;i<numLines * numYincrement;i+=numYincrement) {
//canvas_ctx.beginPath();
canvas_ctx.moveTo(line_x,i + offset);
canvas_ctx.lineTo(line_length,i + offset);
canvas_ctx.stroke();
//canvas_ctx.closePath();
}
}
This should, ideally result in 5 black lines. Instead, the color of the lines seems to fade with each new line (as if it's a gradient!), so that line 5 is gray. If I uncomment canvas_ctx.beginPath(); and canvas_ctx.closePath();, all lines become gray. Why is this happening??
Strokes do overlap from both sides of the coordinates.
var ctx = c.getContext('2d');
ctx.strokeStyle="red";
// draw big
ctx.scale(30, 30);
ctx.beginPath();
ctx.moveTo(5, 0);
ctx.lineTo(5, 10);
ctx.stroke();
drawPixelGrid();
function drawPixelGrid() {
// simply renders where the pixel bounds are
ctx.beginPath();
// remove the zoom
ctx.setTransform(1,0,0,1,0,0);
ctx.strokeStyle = 'gray';
ctx.lineWidth = 2; // avoid the problem we are demonstrating by using a perfect lineWidth ;-)
for(let y=0; y<=300; y+=30) {
ctx.moveTo(0, y);
ctx.lineTo(300, y);
for(let x=0; x<=300; x+=30) {
ctx.moveTo(x, 0);
ctx.lineTo(x, 300);
}
}
ctx.stroke();
}
<canvas id="c" height=300></canvas>
But obviously, a pixel can't be set to two colors at the same time. So browsers apply antialiasing, which will fade your pixel color to an other color, being the result of mixing the background and the foreground color.
So for a black stroke over a white or transparent background, this leads to actual gray pixels being rendered. Here I'll keep using red as an example:
var ctx = c.getContext('2d');
ctx.strokeStyle="red";
// first draw as on a 10*10 canvas
ctx.beginPath();
ctx.moveTo(5, 0);
ctx.lineTo(5, 10);
ctx.stroke();
// zoom it
ctx.imageSmoothingEnabled = 0;
ctx.globalCompositeOperation = 'copy';
ctx.drawImage(c, 0,0,9000,9000);
drawPixelGrid();
// this is not red...
function drawPixelGrid() {
ctx.globalCompositeOperation = 'source-over';
ctx.beginPath();
ctx.setTransform(1,0,0,1,0,0);
ctx.strokeStyle = 'gray';
ctx.lineWidth = 2;
for(let y=0; y<=300; y+=30) {
ctx.moveTo(0, y);
ctx.lineTo(300, y);
for(let x=0; x<=300; x+=30) {
ctx.moveTo(x, 0);
ctx.lineTo(x, 300);
}
}
ctx.stroke();
}
<canvas id="c" height=300></canvas>
One way to avoid it is generally to apply an offset on your coordinates so that the line extends correctly on pixels boundaries. E.g for a 1px lineWidth, you would apply a 0.5 offset:
var ctx = c.getContext('2d');
ctx.strokeStyle="red";
// first draw as on a 10*10 canvas
ctx.beginPath();
ctx.moveTo(5.5, 0); // offset +0.5px
ctx.lineTo(5.5, 10);
ctx.stroke();
// zoom it
ctx.imageSmoothingEnabled = 0;
ctx.globalCompositeOperation = 'copy';
ctx.drawImage(c, 0,0,9000,9000);
drawPixelGrid();
// now we've got a real red
function drawPixelGrid() {
ctx.globalCompositeOperation = 'source-over';
ctx.beginPath();
ctx.setTransform(1,0,0,1,0,0);
ctx.strokeStyle = 'gray';
ctx.lineWidth = 2;
for(let y=0; y<=300; y+=30) {
ctx.moveTo(0, y);
ctx.lineTo(300, y);
for(let x=0; x<=300; x+=30) {
ctx.moveTo(x, 0);
ctx.lineTo(x, 300);
}
}
ctx.stroke();
}
<canvas id="c" height=300></canvas>
But in your case, you are drawing at 0.5px lineWidth, so no offset will be able to get rid of this antialiasing.
So if you want perfect color, choose a correct lineWidth.
I want to transform the head of a dog to turn, but I don't know how to select an entire function and not more and transform this into an animation.
// The function
Head();
rotate();
// this is for the entire canvas, but how to do it specifically for a function
context.rotate(rotation);
rotation += 0.04
I am also not very familiar with animating in html canvas
You need to save() the context before the transformation. Next you call the function that draw the head. Then you restore() the context. In this way the head will be transformed nut not the rest of the canvas.
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let cw = canvas.width = 300,
cx = cw / 2;
let ch = canvas.height = 300,
cy = ch / 2;
let rotation = 0
function background(){
ctx.beginPath();
ctx.fillStyle="gold";
ctx.fillRect(20,20,160,50);
ctx.beginPath();
ctx.fillStyle="gold";
ctx.fillRect(120,220,160,50);
}
function Head(){
ctx.fillStyle = "skyBlue";
ctx.beginPath();
ctx.arc(0,0,40,0,2*Math.PI);
ctx.fill();
ctx.beginPath();
ctx.arc(-15,-5,8,0,2*Math.PI);
ctx.fillStyle="white";
ctx.fill();
ctx.beginPath();
ctx.arc(15,-5,8,0,2*Math.PI);
ctx.fillStyle="white";
ctx.fill();
ctx.beginPath();
ctx.arc(0,0,30,Math.PI/10,9*Math.PI/10);
ctx.strokeStyle="white";
ctx.stroke();
}
function frame(){
requestAnimationFrame(frame);
rotation += 0.04;
ctx.clearRect(-cw,-ch,2*cw,2*ch);
background()
ctx.save();
ctx.translate(cx,cy);
ctx.rotate(rotation);
// The function
Head();
ctx.restore();
}
frame()
canvas{border:1px solid}
<canvas id="canvas"></canvas>
I want to draw one circle and a character with shadow on a canvas in a HTML page while loading the page and recreate the image on a button click. I am using this code:
window.onload = function() {
draw();
};
function draw(){
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
var width = c.width;
var height = c.height;
//DRAW A CIRCLE
var centerX = Math.floor((Math.random() * width));
var centerY = Math.floor((Math.random() * height));
var radius = Math.floor(Math.random() * 50);
var color = '#f11';
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
//DRAW A CHARACTER WITH SHADOW
var c = "S";
ctx.font = "300% Verdana";
ctx.shadowBlur = 20;
ctx.shadowColor = "black";
ctx.shadowOffsetX = 20;
ctx.shadowOffsetY = 20;
ctx.fillStyle = "#111";
ctx.fillText(c, 10, 90);
}
In HTML I am calling draw function onclick() event of a button named Refresh.
For the first time it is giving desired output by drawing one circle and a character with shadow. As I click on the Refresh button it is drawing both the objects with shadow. I dont want to draw shadow of the circle. Can anyone please tell me the mistake I'm doing here.
You may want to use the CanvasRenderingContext2D.save() method :
window.onload = function() {
draw();
};
document.getElementById("canvas").addEventListener('click', draw);
function draw(){
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
var width = c.width;
var height = c.height;
//DRAW A CIRCLE
var centerX = Math.floor((Math.random() * width));
var centerY = Math.floor((Math.random() * height));
var radius = Math.floor(Math.random() * 50);
var color = '#f11';
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
//DRAW A CHARACTER WITH SHADOW
//save the actual context
ctx.save();
var c = "S";
ctx.font = "300% Verdana";
ctx.shadowBlur = 20;
ctx.shadowColor = "black";
ctx.shadowOffsetX = 20;
ctx.shadowOffsetY = 20;
ctx.fillStyle = "#111";
ctx.fillText(c, 10, 90);
//restore it
ctx.restore();
}
canvas{border:1px solid;}
<canvas id="canvas" width="400" height="200"></canvas>
How can I get the same effect on canvas like it's shown in the image below (source: here)
I try something like this LINK
e.preventDefault();
var x = e.pageX;
var y = e.pageY;
if (!drawing) return
ctx.beginPath();
ctx.globalAlpha = .3;
ctx.lineJoin ='round';
ctx.lineCap = 'butt'
ctx.shadowBlur = 0;
//ctx.globalCompositeOperation = "copy";
ctx.moveTo(prev.x, prev.y);
ctx.strokeStyle = '#000';
//ctx.strokeStyle = 'rgba(100,0,0,0.1)';
ctx.lineTo(x, y);
ctx.lineWidth = 20;
ctx.stroke();
ctx.closePath();
prev.x = x;
prev.y = y;
It looks like you almost have the effect you want.
(semi-transparent, overlapping rounded strokes with opacity accumulating where they overlap).
Try changing the globalAlpha to .03 instead of .3.
I've branched your jsFiddle, but I've amended the colour and alpha transparency a bit to get the same colour (ish) as your image :
http://jsfiddle.net/rsc8k/2/
ctx.globalAlpha = .1;
ctx.strokeStyle = '#337799';
Looks pretty similar. Note that that's all the changes I've made on your jsfiddle.
Seemed simple enough to draw circles and text in an HTML5 canvas, but I get non-intuitive behavior. The circles get drawn nice and pretty, then the more circles I draw, the older circles become more and more octagonal shaped. Very strange to me... Also, the text disappears from the old circles and only appears on the last circle drawn. What's the proper way to do this with canvases?
$("#circles_container").on("click", "#circles_canvas", function(event) {
var canvas = document.getElementById('circles_canvas');
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
var w = 16;
var x = event.pageX;
var y = Math.floor(event.pageY-$(this).offset().top);
ctx.fillStyle = "rgb(200,0,0)";
ctx.arc(x, y, w/2, 0, 2 * Math.PI, false);
ctx.fill();
ctx = canvas.getContext("2d");
ctx.font = '8pt Calibri';
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.fillText('0', x, y+3);
}
});
Just add this near the start of your function :
ctx.beginPath();
You were drawing a path always longer.
Demo in Stack Snippets & JS Fiddle (click on the canvas)
var canvas = document.getElementById('circles_canvas');
canvas.addEventListener("click", function(event) {
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
var w = 16;
var x = Math.floor(event.pageX-this.offsetLeft);
var y = Math.floor(event.pageY-this.offsetTop);
ctx.beginPath();
ctx.fillStyle = "rgb(200,0,0)";
ctx.arc(x, y, w/2, 0, 2 * Math.PI, false);
ctx.fill();
ctx.font = '8pt Calibri';
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.fillText('0', x, y+3);
}
})
canvas {
border: 1px solid black;
}
<h1>Click Canvas Below</h1>
<canvas id="circles_canvas"></canvas>