0% found this document useful (0 votes)
3 views

js canvas

The document provides an overview of the HTML5 <canvas> element, detailing its capabilities for drawing graphics directly on web pages without the need for external plugins like Adobe Flash. It covers essential concepts such as canvas coordinates, drawing lines and shapes, fill styles, transformations, and animations using JavaScript. Additionally, it includes examples of how to implement various graphic features, including paths, images, text, and shadows.

Uploaded by

Hạnh Hồng
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

js canvas

The document provides an overview of the HTML5 <canvas> element, detailing its capabilities for drawing graphics directly on web pages without the need for external plugins like Adobe Flash. It covers essential concepts such as canvas coordinates, drawing lines and shapes, fill styles, transformations, and animations using JavaScript. Additionally, it includes examples of how to implement various graphic features, including paths, images, text, and shadows.

Uploaded by

Hạnh Hồng
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Canvas

59 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Introduction
 Canvases enables designers and programmers to create
and place graphics directly onto a web page
 Prior to HTML5, an external plug-in, usually Adobe Flash, was
required to accomplish many of the features that a canvas can
now perform
 Can be used to draw simple lines and geometric figures, but
also to create highly complex and interactive games and
applications
 Absolutely requires the use of JavaScript to function
 <canvas> element:
 <canvas id="drawing" width="500"
height="300"></canvas>

60 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Canvas Coordinates
 2D Cartesian coordinates
 Upper limits of the x and y depend on the width and
height

500px
(0,0) is the (500,0) is the top
top left corner right corner of
of the canvas 300px the canvas

(0,300) is the (500,300) is the


bottom left bottom right
corner of the corner of the
canvas canvas

61 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Lines and Paths
 Obtaining the “context” (CanvasRenderingContext2D):
 const cnv = document.getElementById("drawing");
const ctx = canvas.getContext("2d");

 Draw the line:


 ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(400, 100);
ctx.stroke();

(400, 100)
(100, 100)

62 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Line Options
 ctx.lineWidth = 20;
ctx.strokeStyle = "red";
ctx.lineCap = "square";
ctx.lineJoin = "round";

ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(100, 200);
ctx.lineTo(200, 100);
ctx.stroke();

63 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Closed Paths
 ctx.lineWidth = 20;
ctx.strokeStyle = "red";
ctx.lineCap = "round";
ctx.lineJoin = "round";

ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(100, 200);
ctx.lineTo(200, 100);
ctx.closePath();
ctx.stroke();

64 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
More Line Options
 lineCap = "butt"|"round"|"square"

 lineJoin = "round"|"bevel"|"miter"

 setLineDash(pattern)
 Ex: setLineDash([3, 8, 10, 2])

65 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Filled Shapes
 ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(100, 200);
ctx.lineTo(200, 100);
ctx.fill();

66 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
fill() and stroke() together
 ...
ctx.fill();
ctx.stroke();

 ...
ctx.closePath();
ctx.fill();
ctx.stroke();

 ...
ctx.closePath();
ctx.stroke();
ctx.fill();

67 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Rectangles
 strokeRect(left, top,
width, height)
 fillRect(left, top,
width, height)
 Example:
 ctx.lineWidth = 10;
ctx.strokeStyle = "#f28";
ctx.lineJoin = "round";
ctx.strokeRect(50, 50, 100,
200);
ctx.fillRect(50, 50, 100,
200);

68 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
More Paths
 rect(x, y, width, height)
 ellipse(x, y, rx, ry, rotation, startAng, endAng)
 arc(x, y, r, startAng, endAng)
 arcTo(x1, y1, x2, y2, r)
 quadraticCurveTo(cpx, cpy, x, y)
 bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

arcTo quadraticCurveTo bezierCurveTo

69 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Fill Styles
 fillStyle = color|gradient|pattern;
 Examples:
 ctx.fillStyle = "yellow";
 ctx.fillStyle = "#256f7a";
 ctx.fillStyle = "rgb(127, 0, 255)";
 const img = new Image();
img.src = "pattern.png";
img.onload = function() {
const pat = ctx.createPattern(img, "repeat");
ctx.fillStyle = pat;
};
 const grad = ctx.createLinearGradient(20, 0, 220, 0);
grad.addColorStop(0, 'green');
grad.addColorStop(.5, 'cyan');
grad.addColorStop(1, 'green');
ctx.fillStyle = grad;

70 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Clipping
 clip([path]): turns the current or given path into the
current clipping region

 Example:
 ctx.beginPath();
ctx.arc(100, 75, 50, 0, Math.PI * 2);
ctx.clip();

ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'orange';
ctx.fillRect(0, 0, 100, 100);

71 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Images
 Syntax:
 drawImage(img, dx, dy)
 drawImage(img, dx, dy, dw, dh)
 drawImage(img, sx, sy, sw, sh,
dx, dy, dw, dh)
 Example:
 let img = new Image();
img.src = "picture.jpg";
// or: img.src = "data:image/gif;base64,R0lGODlhCwALA…";

img.onload = function() {
ctx.drawImage(img, 100, 50);
};
 Question: Is it neccessary to set img.src before img.onload?

72 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Text
 Syntax:
 strokeText(text, x, y, [maxWidth])
 fillText (text, x, y, [maxWidth])
 Options:
 font = CSS font value
 textAlign = "left"|"right"|"center"|"start"|"end"
 textBaseline = "alphabetic"|"top"|"middle"|"bottom"
 Examples:
 ctx.font = 'bold 48px serif';
ctx.strokeText('Hello world', 50, 100);
ctx.fillText('Hello world', 250, 90, 140);

strokeText fillText
73 AC2070: Web Design & Programming
Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Shadows
 Use the following properties:
 shadowColor
 shadowBlur
 shadowOffsetX
 shadowOffsetY

74 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Transformations
 Translation:
 translate(x, y)
 Rotation:
 rotate(ang)
 Scaling:
 scale(sx, sy) translate rotate
 By matrix (general case):
𝑚11 𝑚12 𝑑𝑥
𝑚21 𝑚22 𝑑𝑦
0 0 1
 transform(m11, m12, m21, m22, dx, dy)
 Save and restore transformation (and style) state:
 save()
 restore()

75 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Animations
 Principle: When the content changes, notify the browser that
the canvas needs to be updated before the next repaint
→ the browser will invoke a given draw function

 Steps to redraw a frame:


1. Clear the canvas: using clearRect()
2. Save the canvas state: using save()
3. Draw shapes: using window.requestAnimationFrame()
Attn: requestAnimationFrame is valid until the next repaint
4. Restore the canvas state: using restore()

 Question: Why not call the draw function directly in Step 3?

76 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Example: Rotating Dot
const w = canvas.width; function draw() {
const h = canvas.height; ctx.clearRect(0, 0, w, h);
ctx.save();
// initial direction ctx.translate(w/2, h/2);
let dir = 0; ctx.rotate(dir);
ctx.translate(100, 0);
// update direction every 50ms
setInterval(function() { ctx.fillStyle = "red";
dir += 0.02; ctx.beginPath();
ctx.ellipse(0, 0, 10, 10, 0,
// notify the browser to redraw 0, Math.PI*2);

window.requestAnimationFrame(draw); ctx.fill();
}, 50); ctx.restore();
}
// first frame
draw();

77 AC2070: Web Design & Programming


Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology

You might also like