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.
Related
I am attempting to make a dynamic canvas where when the user types text, the canvas rerenders for the text so the canvas width (and height) is the same as the text. I followed some guide that essentially said to create a script like this
Codesandbox.com Live Link: https://codesandbox.io/s/tender-sound-zk5x6h?file=/src/App.js
function ResizeCanvas(textInput) {
const canvas3 = canvasRef.current;
const canvasContext = canvas3.getContext("2d");
canvasContext.font = "40 40px arial";
canvasContext.fillStyle = "red";
canvasContext.textAlign = "left";
canvasContext.fillText(textInput, 0, canvas3.height - 1);
canvas3.width = canvasContext.measureText(textInput).width;
canvas3.style.width = canvas3.width + "px";
canvasContext.font = "40 40px arial";
canvasContext.fillStyle = "red";
canvasContext.textAlign = "left";
canvasContext.fillText(textInput, 0, canvas3.height - 1);
}
However, the bottom text is cut off. I noticed when I add a paddingBottom: "20px" to the canvas element, it doesnt show the rest of the text and increasing the height does not change anything.
How come I cannot see the full p, q letters?
I have a canvas elements in my webpage that is containing some text which I want to edit with text box.For example a text in canvas is "This is a apple" but later I want to change that text like this "Apple is never liked by me" This thing should be done via text box key up event with javascript or jQuery. Please give me some suggestions.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "20px Georgia";
ctx.fillText("This is a apple", 10, 50);
ctx.font = "30px Verdana";
// Create gradient
var gradient = ctx.createLinearGradient(0, 0, c.width, 0);
gradient.addColorStop("0", "magenta");
gradient.addColorStop("0.5", "blue");
gradient.addColorStop("1.0", "red");
// Fill with gradient
ctx.fillStyle = gradient;
ctx.fillText("Big smile!", 10, 90);
</script>
<input id="sourceText1" type=text>
</body>
</html>
I want to change the text with textbox.
Here's some code that will work with your current example. It is however, terribly flawed - I'd like to make that very clear.
0) I've had to add 4 pixels in order to get the erasing rect to cover the text properly. I'm not sure why this is needed, or how to query/calculate this - I used an image editor. If the size of your text was different, I'd imagine you would need to use a different 'magic-number' than 4.
1) The example will break-down if the background is not white, most particularly if you have a pattern, rather than a solid colour.
2) The whole text is erased and redrawn for each keystroke - we should ideally speaking, only be clearing it if necessary. I.e - if the text gets longer and the new text is the same up until the new character, there's nothing to erase.
3) I'm too tired to further examine my code for flaws.
4) You can almost certainly (actually I'm about 99.9999999% sure) find code that does this kind of task already - code which is far more robust and, is production-ready.
Consider this code nothing more than "a hack that works". If I could post it merely as a comment, I would.
Perhaps a better option would be to simply draw the text again, using white as the colour - though I've a feeling that this wont quite work, due to anti-aliasing, which will leave a faint outline - failing to properly cover the existing text.
If the code is unsuitable for you, simply bring it back along with your receipt for a full refund. :laughs:
That said, here you go:
<!DOCTYPE html>
<html>
<head>
<script>
function byId(id){return document.getElementById(id);}
window.addEventListener('load', onDocLoaded, false);
var textPosX = 10, textPosY = 50;
var defaultText = "This is a apple";
var curText = defaultText;
var defaultFont = "20px Georgia";
function onDocLoaded(evt)
{
// add event listener to the input element, this will fire any time (text) input is received
byId('sourceText1').addEventListener('input', onSourceTextInput, false);
var c = byId("myCanvas");
var ctx = c.getContext("2d");
ctx.font = defaultFont;
ctx.fillText(defaultText, textPosX, textPosY);
ctx.font = "30px Verdana";
// Create gradient
var gradient = ctx.createLinearGradient(0, 0, c.width, 0);
gradient.addColorStop("0", "magenta");
gradient.addColorStop("0.5", "blue");
gradient.addColorStop("1.0", "red");
// Fill with gradient
ctx.fillStyle = gradient;
ctx.fillText("Big smile!", 10, 90);
}
function onSourceTextInput(evt)
{
var can = byId('myCanvas');
var ctx = can.getContext('2d');
var curTextWidth, curTextHeight;
curTextWidth = ctx.measureText(curText).width;
curTextHeight = 20;
var curStyle = ctx.fillStyle;
ctx.fillStyle = "white";
ctx.fillRect(textPosX, (textPosY-curTextHeight)+4, curTextWidth, curTextHeight);
ctx.fillStyle = 'BLACK';
ctx.font = defaultFont;
ctx.fillText( this.value, textPosX, textPosY );
ctx.fillStyle = curStyle;
curText = this.value;
}
</script>
</head>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>
<input id="sourceText1" type='text'/>
</body>
</html>
The Image is flickering as I continuously push the button. The problem might be in ctx.clearRect(0,0,100,500) . How can I resolve the problem?
I am trying to animate in HTML 5 canvas.
I need a moving object in canvas and when I push the button, the other moving object follow the previous without flickering.
function draw(x,y){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0,100,500); // This may be the problem
var img=document.getElementById("Image");
ctx.drawImage(img,50,y);
ctx.restore();
y -= 10;
var loopTimer = setTimeout('draw('+x+','+y+')',50);
}
HTML 5
<button onclick="draw(0,500)">Draw</button>
<canvas id="canvas" width="600" height="500">
</canvas>
It looks like the problem may be because you aren't clearing the entire canvas. Try this:
function draw(x,y){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0, canvas.width, canvas.height);
var img=document.getElementById("Image");
ctx.drawImage(img,50,y);
ctx.restore();
y -= 10;
var loopTimer = setTimeout('draw('+x+','+y+')',50);
}
Demo
The image flicker when you press the button more than once, which means you start the setTimeout() more than once. Add a variable to check if it's already been pressed.
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>
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.