Javascript code display text - javascript

Have code for a rectangle with a line through it, I would like to display text under the rectangle. How do I add this into my code? Or can someone point me in the right direction?
<canvas id="main" width="300" height="300"></canvas>
<script>
var canvas = document.getElementById("main");
var context = canvas.getContext('2d');
context.fillStyle = "#008000";
context.rect(0,0,300,300);
context.fill();
context.beginPath();
context.lineWidth = 10;
context.strokeStyle = "blue";
context.lineCap = "round";
context.moveTo( 50, 150);
context.lineTo (250, 150);
context.stroke();
context.closePath();

You can draw text using fillText:
context.fillText("Hello, world!", 50, 50);
For more information, see this article on the Mozilla Developer Network.

I believe you want the fillText function:
context.font="30px Arial";
context.fillText("Hello World",10,50);

Related

How to rotate a rectangle in Javascript

Hi guys, I am working on an assignment where I need to draw an image of an emoticon face.
function sadFace() {
//Drawing the sad face
context.beginPath();
context.fillStyle = "rgb(255,255,0)" //Drawing the face in yellow colour
context.lineWidth = 3;
context.arc(300,300,200,0,Math.PI*4,true);
context.fill();
context.stroke();
//Left Eyebrow
context.beginPath();
context.fillStyle = "rgb(0,0,0)";
context.rect(170,180,90,15);
context.fill();
context.stroke();
This is my current code. How can I rotate the 'eyebrow' of the image firstly, and also rotate the eyebrow without rotating the whole image? Thanks!
You can use affine transformation, like rotation, translation, scale.
First save the current context
context.save()
Set rotation and translation see document
Restore the state
context.restore()
const canvas = document.getElementById("canvas")
const context = canvas.getContext("2d");
context.beginPath();
context.fillStyle = "rgb(255,255,0)" //Drawing the face in yellow colour
context.lineWidth = 3;
context.arc(300,300,200,0,Math.PI*4,true);
context.fill();
context.stroke();
//Left Eyebrow
context.save();
context.translate(210, 188);
context.rotate(30 * Math.PI / 180);
context.beginPath();
context.fillStyle = "rgb(0,0,0)";
context.rect(-45,-8,90,15);
context.fill();
context.stroke();
context.restore();
context.save();
context.translate(380, 188);
context.rotate(-30 * Math.PI / 180);
context.beginPath();
context.fillStyle = "rgb(0,0,0)";
context.rect(-45,-8,90,15);
context.fill();
context.stroke();
context.restore();
<canvas id="canvas" width="500" height="500" />
Explanation:
Since rotating is rotate around the coordinator (O (0, 0), we need to translate first to the position we want to draw:
context.translate(eyeBrowX, eyeBrowY); // eyebrow position here
Then do a rotation:
context.rotate(angleInRadian);
Then draw the rectangle so that the center of the rectangle is O (0, 0) - then it would rotate around its center.
context.beginPath();
context.fillStyle = "rgb(0,0,0)";
context.rect(-width / 2, -height / 2, width, height);
context.fill();
context.stroke();
You don't have to rotate anything. Instead of creating rect just use lines to draw the eyebrows. Tell the line to go get drawn in a diagonal path like this
let canvas = document.getElementById("myCanvas");
let context = canvas.getContext("2d");
context.beginPath();
context.fillStyle = "rgb(255,255,0)" //Drawing the face in yellow colour
context.lineWidth = 3;
context.arc(300,300,200,0,Math.PI*4,true);
context.fill();
context.stroke();
//Left Eyebrow
context.beginPath();
context.moveTo(170,180);
context.lineTo(260,195);
context.lineWidth = 10
context.fillStyle = "rgb(0,0,0)";
context.fill();
context.stroke();
<canvas id="myCanvas" width="800" height="800"></canvas>
In this way you don't need to save the context. By the way the canvas does not allow you to change things individually. You need to clear and redraw. (that how it works for animations for example). If you want more control, and modify things individually you need a rendering library like Pixi.js

How to create html5 canvas for bordered boxes?

I am trying to create below canvas.
Image
my code is below. but I am having trouble to make the canvas look the like the screenshot above. can anyone help me then?
thanks though
<html>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
var canvas;
var canvasContext;
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
canvasContext.fillStyle = 'blue';
canvasContext.fillRect(0,0,canvas.width,canvas.height);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(355,350,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(190,350,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(520,350,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(355,200,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(190,200,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(520,200,120,90);
}
</script>
</html>
.fillRect creates a filled region of color. However, .rect creates a "shape" that you can then use the .fill() and .stroke() methods upon.
In the below example if converted creation into a loop for brevity
var canvas;
var canvasContext;
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
canvasContext.fillStyle = 'blue';
canvasContext.fillRect(0,0,canvas.width,canvas.height);
var height = 90;
var width = 120;
var leftOffset = 190;
var topOffset = 200;
for(var x = 0; x < 6; x++){
canvasContext.beginPath();
canvasContext.rect(leftOffset,topOffset,width,height);
canvasContext.fillStyle = 'grey';
canvasContext.fill();
canvasContext.lineWidth = 4;
canvasContext.strokeStyle = 'lightblue';
canvasContext.stroke();
leftOffset += 165;
if(x === 2){
leftOffset = 190;
topOffset = 350;
}
}
}
JSFIDDLE
This tutorial on HTML5 Canvas rectangles is very handy
To add the text, you would append the following after (or before) the rect creating loop
canvasContext.beginPath();
canvasContext.font = '20pt Arial';
canvasContext.textAlign = 'center';
canvasContext.fillStyle = 'white';
canvasContext.shadowColor = 'black';
canvasContext.shadowOffsetX = 4;
canvasContext.shadowOffsetY = 4;
canvasContext.fillText('CHOOSE A SCENE TO COLOR', canvas.width/2,55);
UPDATED FIDDLE
Tutorials for text align, text shadow, and text.
Try something like this, use a function to draw a rectangle with exactly the border you want. The trick is to use .rect instead of fillRect so that you can use .stroke() immediately after.
<html>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
function draw_bordered_rect(context, x, y, w, h) {
context.rect(x, y, w, h);
context.fillStyle = "grey";
context.fill();
context.lineWidth = 3;
context.strokeStyle = "lightblue";
context.stroke();
}
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
canvasContext.fillStyle = 'blue';
canvasContext.fillRect(0, 0, canvas.width, canvas.height);
canvasContext.font = '25pt Arial';
canvasContext.textAlign = 'center';
//drop shadow 2px to the left and 2px below the white text
canvasContext.fillStyle = "black";
canvasContext.fillText('CHOOSE A SCENE TO COLOR', canvas.width/2-2, 82);
//actual text ontop of the drop shadow text
canvasContext.fillStyle = 'white';
canvasContext.fillText('CHOOSE A SCENE TO COLOR', canvas.width/2, 80);
draw_bordered_rect(canvasContext, 355, 350, 120, 90);
draw_bordered_rect(canvasContext, 190, 350, 120, 90);
draw_bordered_rect(canvasContext, 520, 350, 120, 90);
draw_bordered_rect(canvasContext, 355, 200, 120, 90);
draw_bordered_rect(canvasContext, 190, 200, 120, 90);
draw_bordered_rect(canvasContext, 520, 200, 120, 90);
}
</script>
</html>
Looks like:
I have some code to design canvas box in HTML5. I think you should try this one, I hope it will help you to design your canvas box. I think you should use JavaScript mehtod context.fillRect as i am giving you Js Fidler Lind here
HTML Code
<canvas id="myCanvas" width="500" height="400">
<!-- Insert fallback content here -->
</canvas>
JavaScript Code
var canvas = $("#myCanvas");
var context = canvas.get(0).getContext("2d");
// Set rectangle and corner values
var rectX = 50;
var rectY = 50;
var rectWidth = 100;
var rectHeight = 100;
var cornerRadius = 20;
// Reference rectangle without rounding, for size comparison
context.fillRect(200, 50, rectWidth, rectHeight);
// Set faux rounded corners
context.lineJoin = "round";
context.lineWidth = cornerRadius;
// Change origin and dimensions to match true size (a stroke makes the shape a bit larger)
context.strokeRect(rectX+(cornerRadius/2), rectY+(cornerRadius/2), rectWidth-cornerRadius, rectHeight-cornerRadius);
context.fillRect(rectX+(cornerRadius/2), rectY+(cornerRadius/2), rectWidth-cornerRadius, rectHeight-cornerRadius);
// You can do the same thing with paths, like this triangle
// Remember that a stroke will make the shape a bit larger so you'll need to fiddle with the
// coordinates to get the correct dimensions.
context.beginPath();
context.moveTo(400, 60);
context.lineTo(440, 140);
context.lineTo(360, 140);
context.closePath();
context.stroke();
context.fill();
This javascript code will design canvas box just like below g]iven image

How to make my drawing move inside HTML5 canvas?

I have a HTML5 canvas and Javascript. How can I make it move like move it's arms and feet?
I tried Googling for some tutorials but failed.
Attached here is my image and my codes:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="canvascss.css">
</head>
<body>
<div>
<canvas id="canvas" width="400px" height="300px" >
Your browser does not support HTML5 Canvas element
</canvas>
</div>
<script>
var canvas = document.getElementById("canvas");
if (canvas.getContext("2d")) { // Check HTML5 canvas support
context = canvas.getContext("2d"); // get Canvas Context object
context.beginPath();
context.fillStyle = "black"; // #ffe4c4
context.arc(200, 50, 30, 0, Math.PI * 2, true); // draw circle for head
context.fill();
context.beginPath();
context.strokeStyle = "black"; // color
context.lineWidth = 3;
context.arc(200, 50, 20, 0, Math.PI, false); // draw semicircle for smiling
context.stroke();
// eyes
context.beginPath();
context.fillStyle = "black"; // color
context.arc(190, 45, 3, 0, Math.PI * 2, true); // draw left eye
context.fill();
context.arc(210, 45, 3, 0, Math.PI * 2, true); // draw right eye
context.fill();
// body
context.beginPath();
context.moveTo(200, 80);
context.lineTo(200, 180);
context.strokeStyle = "black";
context.stroke();
// arms
context.beginPath();
context.strokeStyle = "black"; // blue
context.moveTo(200, 80);
context.lineTo(150, 130);
context.moveTo(200, 80);
context.lineTo(250, 130);
context.stroke();
// legs
context.beginPath();
context.strokeStyle = "black";
context.moveTo(200, 180);
context.lineTo(150, 280);
context.moveTo(200, 180);
context.lineTo(250, 280);
context.stroke();
}
</script>
</body>
</html>
Result:
From HTML5 Canvas Animation with requestAnimFrame:
To create an animation using HTML5 Canvas, we can use the
requestAnimFrame shim which enables the browser to determine the
optimal FPS for our animation. For each animation frame, we can
update the elements on the canvas, clear the canvas, redraw the
canvas, and then request another animation frame.
In short your point of departure is the following:
requestAnimationFrame
You will need a javascript function to CHANGE aspects of your starting image, and then to call that javascript code at regular intervals.
setInterval is another key word to google and learn from.

Canvas elements cut off at the

When I place a square on the canvas at 0,0 coords the top left is cut off:
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');
context.strokeStyle = 'blue';
context.rect(0, 0, 200, 100);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
<canvas id="c" width="500" height="500"></canvas>
Why is this?
It's because half the stroke is inside the rect.fill and the other half of the stroke is outside the rect.fill.
Kind of like css borders, you must account for them when sizing/positioning.
In canvas's case, the stroke is always half-in / half-out the object.

Is there a way to tile a background image over a canvas path?

For example, I have a canvas in a page with some kind of a path. It is created by javascript this way:
var context = $('#some_canvas').getContext('2d');
context.beginPath();
context.lineWidth = 5;
context.strokeStyle = '#000000';
context.moveTo(0, 0);
context.lineTo(100, 100);
context.stroke();
Is there a way to make the path that appears after this command to have some tiled background image?
I believe you're looking for the createPattern() method:
var pattern = new Image;
pattern.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAARCAIAAABbzbuTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAZtJREFUeNqMUs+rAVEUvjNG2MhClOUsppSEjbWFpOwtMIv5B2ZhZqkkZKkpe+XPYKtsbSxsZIGaQpgi4r3Pu5p3eV45dW/nnPt959zzg5RKpU6n8/WxkHq9LghCs9n8lICjKAohpFwuf0LgcCzLSqfTo9FIVVVd10He7XbX6/V8Pu/3e47jcB+Px0AgkEqlCOXNZjNJkgB1/wg+6XA4ACXPomkasXM1Gg3yj4AZi8WAHgwGgu1dLpcvOKRKJBLZbDaTyYDgdDrvXjtDLpd7yT6dTv8WzdNnaPP53A6Mezgc+v3+N/+jvO12GwwGqQfFYJRQksnker1+MwfIZDLxeDwA+Xy+xWIBT6VSgYk+Hg4HlvAoerVaodNQ8vl8KBSCUqvVAG2326g4EolsNhuYGNQjQ6/XAwh9GI/HbDxZltn/o2OPDBgctaPRKIsQRZEqWJxisXg3aaRCoQBvv99nw59Op3A4DH+1Wu12u09FYwh4w/6wBGwUOhuPx6FfLpfb7fZbtGEYpmnyPM/+x+v1tlotl8sFHdtFnd8CDACAg6Y2weEZQQAAAABJRU5ErkJggg==";
pattern.onload = function () {
var context = $('#some_canvas').getContext('2d');
context.beginPath();
context.lineWidth = 16;
context.strokeStyle = context.createPattern(pattern, 'repeat');
context.moveTo(0, 0);
context.lineTo(150, 150);
context.stroke();
};

Categories