I would like to run a text countdown on canvas but last I checked there was no way to write text to a canvas.
I would like to know if anyone else has come-across an implementation where I could do a numerical countdown from 60 to 0 on the canvas.
$(function () {
var width = 200;
var height = 200;
$('canvas').width(width).height(height);
var ctx = $('canvas')[0].getContext('2d');
var i = 60;
(function draw() {
with(ctx) {
fillStyle = '#000';
fillRect(0, 0, width, height);
fillStyle = '#0f0';
font = 'bold 20px Arial';
fillText(i, 100, 50)
fill();
}
if (!(i--)) return;
setTimeout(draw, 1000);
})();
});
see in action
It is possible to draw text in canvas 2D. If you look at the w3c API documentation you can see the fillText method on context which allows you do draw text, and the font property lets you control the appearance.
Do note: not all canvas 2D implementations support the text API - I know that iOS didn't do it in the past.
This page suggests that it is indeed possible to write text on a canvas.
Related
i have created a canvas and wrote a text over it and i want to know how i should make the text copyable
i hope that someone has the solution
thank you
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.height = '2000';
canvas.width = '2000';
ctx.fillStyle = "black";
ctx.font = "bolder 14px Arial";
ctx.fillText("Text ", canvas.width /2,canvas.height/2);
You can't. It's like you're a painter and you're painting on your canvas. Differently from svg, if you paint something you won't be able to distinguish it from other painted elements.
Otherwise, you can add a timer or a for cycle and make it update every ms.
I want to change the line width in canvas from 5 to 10 from a click event but it's not working in JavaScript
function draw(e) {
if (!painting) {
return;
}
exitdraw(e);
c.lineWidth = 5;
c.lineTo(e.clientX, e.clientY);
c.lineCap = 'round';
c.strokeStyle = 'aqua';
c.stroke();
c.beginPath();
c.moveTo(e.clientX, e.clientY);
}
//this is the listener i want to change the linewidth
var canvas = document.querySelector('#canvas');
var btn = document.getElementById('button');
btn.addEventListener('click',function(){
canvas.getContext('2d').lineWidth = 10;
})
<button onclick="changeWidth()">Change Width</button>
<br />
<canvas height="150" id="canvas" width="200"></canvas>
<script>
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var lineWidth = 5;
function draw() {
ctx.beginPath();
ctx.lineWidth = lineWidth;
ctx.arc(100, 75, 32, 0, 2 * Math.PI);
ctx.stroke();
}
draw();
function changeWidth() {
lineWidth = 10;
draw();
}
</script>
Canvas doesn't store references to what you draw on it so it's impossible to change property that will affect what you draw.
What I mean is in order to change some drawing in your canvas you should render it again with your new style.
Because you use client data on your draw function you should store the data (clientX/Y etc...) in variables (or you may prefer one object that stores all data) and call that function again, but you need to refactor your function to get lineWidth as a param.
Trouble is, you are changing the value after content is drawn. For changes to take affect, you may want to redraw the content after a change. Like:
btn.addEventListener('click',function(){
canvas.getContext('2d').lineWidth = 10;
draw(); // apply changes by redrawing
})
And of course you should omit the c.lineWidth = 5 line from draw function to not to override change. Perhaps do c.lineWidth = 5 in a initializer function ot smt as a default value.
thanks you all for help but i solved it just saved the value in variable and manipulate it like #Whatatimetobealive said
Ok, I've noticed this bug happen not only in the following code(which is just to illustrate), but every code I've written for canvas;
basically, in chrome(I didn't test other browsers),
once you shift your current tab to either a different pc screen, or simply if you have a few tabs in a row and decide to make a new window out of your current tab,
the canvas itself fails to draw. it is stuck and no reason is given in the console.
Here is a GIF of it happening:
http://gifmaker.cc/PlayGIFAnimation.php?folder=2016081601ZEuvXaZnxC2T9fHNNqSW3l&file=output_f72O1H.gif
Just a simple canvas code if you want to try it out:
<canvas id="canvas" width="500" height="400" style="border:1px solid #000000;"></canvas>
<script>
// grab the canvas and context
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// inital coordinates of the black square
var x = 0;
var y = 200;
// speed of the movement in x- and y-direction
// actual no movement in y-direction
var vX = 1;
var vY = 0;
// width and height of the square
var width = 10;
var height = 10;
function animate() {
// clear
// comment this clear function to see the plot of the sine movement
ctx.clearRect(0, 0, canvas.width, canvas.height);
x += vX;
y += vY;
// if the block leaves the canvas on the right side
// bring it back to the left side
if(x>500) {
x = 0;
}
ctx.fillRect(x, y, width, height);
setTimeout(animate, 33);
}
// call the animate function manually for the first time
animate();
</script>
Some sites fixed this bug but I don't know if I am allowed to link them here.
I'm trying to draw a canvas with width x*100px and height y*100px
var x=6,y=5;
var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');
canvas.style.width=(100*x)+"px";
canvas.style.height=(100*y)+"px";
for(var i=0;i<x;i++)
for(var j=0;j<y;j++)
{
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (i*100, j*100, 100, 100);
ctx.fillStyle = "rgb(0,0,0)";
ctx.strokeRect(i*100, j*100, 100, 100);
}
jsfiddle
but it looks like the width and height of each tile in the grid are not 100 px, Why is that? and how can I set the width of each tile exactly to 100px?
Use this instead:
canvas.width=(100*x);
canvas.height=(100*y);
It seems a bit strange, but canvas is one element type that does not use CSS styling for its width and height. The number of available physical pixels is very relevant to the way that it draws, so it can't be left as a transient, derived CSS value (ie, width: calc(300vw - 100% - 20px);). That said, it's usually a good idea to have width/height change on a browser resize if you're making the web page responsive.
I have created a basic shape in HTML canvas element which works fine.
The problem occurs when I resize the canvas, all the drawing in the canvas disappears. Is this the normal behavior? or is there a function that can be used to stop this?
One way to fix this could be to call drawing function again on canvas resize however this may not be very efficient if there is huge content to be drawn.
What's the best way?
Here is the link to sample code https://gist.github.com/2983915
You need to redraw the scene when you resize.
setting the width or height of a canvas, even if you are setting it to the same value as before, not only clears the canvas but resets the entire canvas context. Any set properties (fillStyle, lineWidth, the clipping region, etc) will also be reset.
If you do not have the ability to redraw the scene from whatever data structures you might have representing the canvas, you can always save the entire canvas itself by drawing it to an in-memory canvas, setting the original width, and drawing the in-memory canvas back to the original canvas.
Here's a really quick example of saving the canvas bitmap and putting it back after a resize:
http://jsfiddle.net/simonsarris/weMbr/
Everytime you resize the canvas it will reset itself to transparant black, as defined in the spec.
You will either have to:
redraw when you resize the canvas, or,
don't resize the canvas
One another way is to use the debounce if you are concerned with the performance.
It doesnt resize or redraw every position you are dragging. But it will resize only when the it is resized.
// Assume canvas is in scope
addEventListener.("resize", debouncedResize );
// debounce timeout handle
var debounceTimeoutHandle;
// The debounce time in ms (1/1000th second)
const DEBOUNCE_TIME = 100;
// Resize function
function debouncedResize () {
clearTimeout(debounceTimeoutHandle); // Clears any pending debounce events
// Schedule a canvas resize
debounceTimeoutHandle = setTimeout(resizeCanvas, DEBOUNCE_TIME);
}
// canvas resize function
function resizeCanvas () { ... resize and redraw ... }
I had the same problem. Try following code
var wrapper = document.getElementById("signature-pad");
var canvas = wrapper.querySelector("canvas");
var ratio = Math.max(window.devicePixelRatio || 1, 1);
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;
It keeps the drawing as it is
One thing that worked for me was to use requestAnimationFrame().
let height = window.innerHeight;
let width = window.innerWidth;
function handleWindowResize() {
height = window.innerHeight;
width = window.innerWidth;
}
function render() {
// Draw your fun shapes here
// ...
// Keep this on the bottom
requestAnimationFrame(render);
}
// Canvas being defined at the top of the file.
function init() {
ctx = canvas.getContext("2d");
render();
}
I had the same problem when I had to resize the canvas to adjust it to the screen.
But I solved it with this code:
var c = document.getElementById('canvas');
ctx = c.getContext('2d');
ctx.fillRect(0,0,20,20);
// Save canvas settings
ctx.save();
// Save canvas context
var dataURL = c.toDataURL('image/jpeg');
// Resize canvas
c.width = 50;
c.height = 50;
// Restore canvas context
var img = document.createElement('img');
img.src = dataURL;
img.onload=function(){
ctx.drawImage(img,20,20);
}
// Restote canvas settings
ctx.restore();
<canvas id=canvas width=40 height=40></canvas>
I also met this problem.but after a experiment, I found that Resizing the canvas element will automatically clear all drawings off the canvas!
just try the code below
<canvas id = 'canvas'></canvas>
<script>
var canvas1 = document.getElementById('canvas')
console.log('canvas size',canvas1.width, canvas1.height)
var ctx = canvas1.getContext('2d')
ctx.font = 'Bold 48px Arial'
var f = ctx.font
canvas1.width = 480
var f1 = ctx.font
alert(f === f1) //false
</script>