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>
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'm just starting out with a game that I'm trying to do for a fun little project. I'm still new to canvas and was just wondering how I would be able to make this red square move via arrow keys? I understand the keyupevent but wasn't exactly sure how to incorporate it with canvas. Thanks in advance
<canvas id="myCanvas" height="400" width="400" style="border: 1px solid black"></canvas>
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.translate(120,120);
ctx.lineTo(0,0);
ctx.lineTo(160,0);
ctx.lineTo(160,160);
ctx.lineTo(0,160);
ctx.lineTo(0,0);
ctx.fillStyle = "red";
ctx.fill();
ctx.stroke();
document.addEventListener('keydown', function(event) {
console.log(event.keyCode);
if (event.keyCode == 37) {
ctx.clearRect(0, 0, c.width, c.height);
ctx.translate(0,0);
}
I've putted the shape you draw in a function so that I can call it again after you clear the canvas on key down. Also since you are translating the context you need to clear from (-120, -120). I hope it helps.
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
ctx.translate(120,120);
myShape()
document.addEventListener('keydown', function(event) {
console.log(event.keyCode);
if (event.keyCode == 37) {
ctx.clearRect(-120, -120, canvas.width + 120, canvas.height + 120);
ctx.translate(-120,-120);
myShape()
}});
function myShape(){
ctx.beginPath();
ctx.lineTo(0,0);
ctx.lineTo(160,0);
ctx.lineTo(160,160);
ctx.lineTo(0,160);
ctx.lineTo(0,0);
ctx.fillStyle = "red";
ctx.fill();
ctx.stroke();}
<canvas id="myCanvas" height="400" width="400" style="border: 1px solid black"></canvas>
First: you have to rerender the canvas every time something changed (at least the part that changed).
Second although keydown re-fires while you keep the button pressed, you'd want a more consistent update cycle; like requestAnimationFrame or setInterval. And then later you can also account for the little inconsistencies in these intervals by taking the time since the last function call/update into account.
Then you'd want to introduce a keyState that stores the current state of multiple buttons, so that you can check that outside of the actual keydown/keyup event.
const isKeyDown = {};
document.onkeydown = document.onkeyup = function(e){
isKeyDown[e.which] = isKeyDown[e.key] = e.type === "keydown";
};
and as a second step, you could introduce velocity to the object with friction or gravity. So your button presses don't determine the actual movement, but "act a force" onto the current movement of your object.
I'm trying to run a simple truck simulator (sorry for the liking of trucks), but when I try, it seems to not work (also no errors). However, when I run the entire code in the edit section of Bill Mill's Canvas Tutorial, it works. In case if you say it's my browser, this doesn't show "Oops...":
<canvas id="canvas" width="420" height="440" style="border: 1px solid #000;">Oops...
JS:
/*Truck Driving Simulator**/
//set up the canvas
var c = document.getElementById("canvas");
var w = 420;
var h = w+20;
var ctx = c.getContext('2d');
var t = tr(250,250,20,40,'blue');
function tr(iX,iY,iR,iColor){
return{
drawmove: function(){
ctx.beginPath();
ctx.arc(iX, iY, iR, 0, Math.PI*2, true);
ctx.fillStyle = iColor;
ctx.fill();
ctx.closePath();
}
}
}
function p(){
t.drawmove();
}
function init(){
setInterval(function(){
p();
}, 60);
}
init();
JSFiddle: https://jsfiddle.net/yey4xdoq/
Also, even though it shows in the fiddle, it doesn't on my PC.
I:
1. Made sure my browser supports the canvas tag
2. Correctly linked my Js
3. Correctly called the canvas
Hey Im experimenting with some html5 animation and so far I have a square that "falls" whenever I press the button. I was wondering how i could have it go back to the top when it hits the bottom and fall again.
My current code is:
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="200" height="400" style="border:1px solid black;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
function draw (x,y){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.save();
var side = 10
var up = 10
ctx.clearRect(0,0,200,400);
ctx.fillStyle = "#FF0000";
ctx.fillRect(x,y,up,side);
ctx.restore();
y += 5;
var loopTimer = setTimeout('draw('+x+','+y+')',30);
}
</script>
<button onclick="draw(0,0)">draw</button>
</body>
</html>
Using your variables y, you can simply check if it is below the height of the canvas height.
if( y > c.height ){ // use the canvas height, not the context height
y = 0;
}
Also, the way you're currently calling the timer is a bit inefficient. Instead of :
var loopTimer = setTimeout('draw('+x+','+y+')',30);
I would recommend
var loopTimer = setTimeout(function(){ draw(x,y); },30);
Here's a working example: http://jsfiddle.net/vwcdpLvv/
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.