Why isn't rectangle black in HTML 5 canvas? - html

Below is a simple HTML 5 page with a canvas tag. On the canvas a rectangle is drawn in black, and black text is shown. But for some reason, the rectangle is actually grey. To make it black, I have to draw it 2 or 3 times on top of itself. That seems to indicate there is some sort of alpha issue going on, but I don't know why that would be.
ALSO, the line width looks quite a bit more than 1px wide.... ?
Can anyone show me what I'm doing wrong?
function draw()
{
var canvas = document.getElementById('tutorial');
if (canvas.getContext)
{
var ctx = canvas.getContext('2d');
//ctx.globalAlpha = 1;
//ctx.globalCompositeOperation = "source-over";
ctx.lineWidth = "1";
ctx.strokeStyle = "#000000";
ctx.strokeRect(100, 100, 50, 50); //appears grey
ctx.font = "22px Arial";
ctx.fillStyle = "#000000";
ctx.fillText("test", 120, 120); //appears black as expected
}
}

Your line looks fat and grey as it is overlapping pixels when it is drawn - i.e. your line straddles two pixels. If you change your code to:
ctx.strokeRect(100.5, 100.5, 50, 50);
You'll see a solid black line.
See this page for more information: http://diveintohtml5.info/canvas.html#paths

Related

HTML5 canvas apply color to image where shape overlays

I have this image drawn to a HTML5 canvas:
What I want to do is apply color to just a part of it.
The part where I want to apply color is defined by the following overlay image:
So, basically, I would like to guide my coloring by the overlay. So where the overlay pixels meets the main image pixels I should apply a color on the main image. At least that's how I see it working.
Notice that the overlay matches the whole image except for the lacing.
The catch is that I would like to retain the main image texture while applying the color. You can see that it has a leather texture and a "real" feel which I want to keep.
Can you please show me some methods of achieving this or share some thoughts?
Thank you!
globalCompositeOperation is your friend here.
Basically, you draw your overlay, then you set the gCO to 'source-atop' composite mode, which will make all your future drawings to only stay where there were already opaque pixels drawn, so it is important that your overlay has transparent parts.
So then you just fill a rectangle of your desired command, and finally you draw your original image, either behind, or blended to the new shape we just created.
var ctx = canvas.getContext('2d');
var loaded = 0;
function onload(){
if(++loaded === 2){
canvas.width = this.width;
canvas.height = this.height;
ctx.font = "40px sans-serif";
draw();
}
}
var original = new Image();
var overlay = new Image();
original.onload = overlay.onload = onload;
original.src = 'https://i.stack.imgur.com/vIKpI.png';
overlay.src = 'https://i.stack.imgur.com/10Tre.png';
// list of blending modes.
// Note that destination-over is a composite mode,
// which place the new drawings behind the already-there ones
var currentMode = 0;
var modes = ['destination-over', 'lighter', 'multiply', 'screen', 'overlay', 'darken',
'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light',
'exclusion', 'hue', 'saturation', 'color', 'luminosity' ];
function draw(){
// switch between different Blending modes
var mode = modes[currentMode];
currentMode = (currentMode+1)%(modes.length);
// clear previous
ctx.clearRect(0,0,canvas.width, canvas.height);
// draw our overlay
ctx.drawImage(overlay, 0,0);
// this will keep new drawings only where we already have existing pixels
ctx.globalCompositeOperation = 'source-atop';
ctx.fillStyle = 'red';
ctx.fillRect(0,0,canvas.width, canvas.height);
// now choose between the list of blending modes
ctx.globalCompositeOperation = mode;
// draw our original image
ctx.drawImage(original, 0,0);
// go back to default
ctx.globalCompositeOperation = 'source-over';
// just so we can know which one is shown
ctx.fillStyle = 'black';
ctx.fillText(mode, 40,40)
// do it again
setTimeout(draw, 1000)
}
canvas{
width: 100%;
}
<canvas id="canvas"></canvas>

html5 canvas text slide in behind nothing

I want to have html5 canvas text slide in behind nothing, its an effect where text appears like coming out behind some obstacle, but the obstacle is invisible.
Here is some youtube video showing how to do it in after effect:
https://www.youtube.com/watch?v=KIYMy7vLLRo
I know how to slide a text along canvas, and one idea I got is having two canvases on top of each other, and top canvas is smaller and contains the text that is initially out of canvas and slides in. But if there is a way to do it with just one canvas that would be great.
You can using a clipping path to mask out part of the text.
Save the existing clipping path using the save() method. Create a shape/path and make it the new clipping path using the clip() method. Draw your text. Store the previous clipping path using the restore() method.
For example, suppose your canvas is 100 pixels by 100 pixels. The following will draw text on only the left side of the canvas.
context.save();
context.rect(0, 0, 50, 100);
context.clip();
context.fillText("Draw some text.", 30, 50);
context.restore();
jsFiddle : https://jsfiddle.net/CanvasCode/vgpov2yk/3
var c = document.getElementById('myCanvas');
var ctx = c.getContext("2d");
// Positions for the text startint off
var xText = -100;
var yText = 150;
// This will update the canvas as fast as possible (not good)
setInterval(function () {
// Clear the canvas
ctx.fillStyle = "#F0F";
ctx.fillRect(0, 0, c.width, c.height);
ctx.save()
// We create a clip rect
ctx.rect(200,0,400,400);
ctx.clip();
// Draw text
ctx.fillStyle = "#FFF";
ctx.font = "30px Arial";
ctx.fillText("Hello World", xText, yText);
ctx.restore();
// Increase the text x position
if (xText < 200) {
xText += 0.5;
}
}, 15);
All you have to do is use a clip rect which is like a mask in image editing.

Context scaling breaks some drawing

I'm trying to draw on a virtual canvas of proportions 1x1 so that I don't have to constantly multiply out the actual dimensions.
This works perfectly when I draw circles, but it would appear as though it does not work well with rectangles, and I'm not sure why.
When I have the following code:
var canvas = this.canvas;
var ctx = canvas.getContext("2d");
ctx.scale(this.canvas.width, this.canvas.height);
ctx.beginPath();
ctx.arc(.5, .5, .1, 0, 2*Math.PI);
ctx.fillStyle = "red";
ctx.fill();
It works fine, and the circle scales with the canvas.
However, when I merely change it to the following:
var canvas = this.canvas;
var ctx = canvas.getContext("2d");
ctx.scale(this.canvas.width, this.canvas.height);
ctx.fillStyle = "blue";
ctx.fillRect(0,0, .0001, .001);
ctx.beginPath();
ctx.arc(.5, .5, .1, 0, 2*Math.PI);
ctx.fillStyle = "red";
ctx.fill();
the rectangle takes up the entirety of the screen and even covers up the circle, even though the circle is drawn after the rectangle. It should, obviously, be taking up a very minute amount of space on the canvas.
It might be worth noting that this occurs in a game loop.
However, the following works as expected, with a red circle appearing above a blue backdrop
var canvas = this.canvas;
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0,0, 50, 50);
ctx.beginPath();
ctx.arc(10, 10, 20, 0, 2*Math.PI);
ctx.fillStyle = "red";
ctx.fill();
If you're calling this repeatedly in a game loop, the scale method will increase the scale of your transform, every time through the loop. So you end up with everything growing. Since you're not showing your actual code, it's hard to tell why the circle isn't affected.
Try calling scale() only once, or use save() and restore(), or just reset the transform at the start of the loop, before calling scale():
ctx.setTransform(1, 0, 0, 1, 0, 0);

Canvas rectangle with 3D effect border

(Refer to image)
First part of image shows div with raised borders(using -webkit-box-shadow,box-shadow properties). I want to give same effect to rectangle drawn using HTML5 canvas element.
Is it any way to acieve this??
That's possible, try something like this:
context.rect(50, 50, 100, 100);
context.fillStyle = 'white';
context.shadowColor = 'black';
context.shadowBlur = 25;
context.shadowOffsetX = 10;
context.shadowOffsetY = 10;
context.fill();
Working Example

Draw single pixel line in html5 canvas

When i try to draw single pixel black line with the following code:
context.strokeStyle = '#000';
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.lineWidth = 1;
context.stroke();
context.closePath();
I have more then one pixel line with gray border. How to fix it?
Here is an example http://jsfiddle.net/z4VJq/
Call your function with these coordinates instead: drawLine(30,30.5,300,30.5);. Try it in jsFiddle.
The problem is that your color will be at an edge, so the color will be halfway in the pixel above the edge and halfway below the edge. If you set the position of the line in the middle of an integer, it will be drawn within a pixel line.
This picture (from the linked article below) illustrates it:
You can read more about this on Canvas tutorial: A lineWidth example.
You have to use context.translate(.5,.5); to offset everything by half a pixel. Its easy way for fix your problem
var canvas = document.getElementById("canvas1");
var context1 = canvas.getContext('2d');
context1.strokeStyle = '#000';
context1.beginPath();
context1.moveTo(10, 5);
context1.lineTo(300, 5);
context1.stroke();
var canvas2 = document.getElementById("canvas2");
var context2 = canvas2.getContext('2d');
context2.translate(.5,.5);
context2.strokeStyle = '#000';
context2.beginPath();
context2.moveTo(10, 5);
context2.lineTo(300, 5);
context2.stroke();
<div><canvas height='10' width='300' id='canvas1'>Обновите браузер</canvas></div>
<div><canvas height='10' width='300' id='canvas2'>Обновите браузер</canvas></div>