We can also use Canvas to draw the image with Rectangle simultaneously.
Version
HTML 5
Canvas
The picture is displayed by Canvas, not by <img>
, and the rectangle is drawn by Canvas, too.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Canvas Lab</title>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script>
let context = document.querySelector('#canvas').getContext('2d')
context.canvas.width = innerWidth
context.canvas.height = innerHeight
let image = new Image()
image.src = 'https://konvajs.org/assets/yoda.jpg'
image.onload = () => {
context.drawImage(image, 5, 5)
context.strokeStyle = 'red'
context.lineWidth = 2
context.strokeRect(40, 15, 120, 135)
}
</script>
</html>
Line 9
<canvas id="canvas"></canvas>
- Use HTML’s
<canvas>
tag to draw image - Add
id
to control the<canvas>
tag
Line 12
let context = document.querySelector('#canvas').getContext('2d')
context.canvas.width = innerWidth
context.canvas.height = innerHeight
- Use
querySelector()
to getcanvas
element, andgetContext()
to get its2d
context - Set Canvas’s width and height by
window
‘sinnerWidth
andinnerHeight
Line 17
let image = new Image()
image.src = 'https://konvajs.org/assets/yoda.jpg'
image.onload = () => {
context.drawImage(image, 5, 5)
context.strokeStyle = 'red'
context.lineWidth = 2
context.strokeRect(40, 15, 120, 135)
}
- Both
drawImage()
andstrokeRect()
are written onload
event
Conclusion
- We don’t have to use any packages to use Canvas API to draw the image with a rectangle