search
HomeWeb Front-endCSS Tutorialcss3 implements drawing pictures onto canvas (code example)

This article will introduce you to the method of drawing pictures on the canvas, which is suitable for use on PC and mobile terminals. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Draw a picture on the canvas

<canvas id="myCanvas" width="1000px" height="200px" >您的浏览器不支持canvas标签。</canvas>
var canvas = document.getElementById("myCanvas");
//获取画笔
var ctx=canvas.getContext(&#39;2d&#39;);
//声明Image对象
var img=new Image();
//获取img路径
img.src="img/num.png";
//把图片画到画布上
img.onload=function(){
	ctx.drawImage(img,57,0,57,64);
}

If you want to put several different pictures on the canvas, if there are several pictures, you need to declare the object several times and obtain the path several times. Paint on the canvas several times.

The following are 6 pictures I drew on the canvas,

var canvas = document.getElementById("myCanvas");
//获取画笔
			var ctx=canvas.getContext(&#39;2d&#39;);
			//声明Image对象
			var img=new Image();
			var img1=new Image();
			var img2=new Image();
			var img3=new Image();
			var img4=new Image();
			var img5=new Image();
			//获取img路径
			img.src="img/num.png";
			img1.src="img/num/1.png"
			img2.src="img/num/4.png"
			img3.src="img/num/2.png"
			img4.src="img/num/5.png"
			img5.src="img/num/7.png"
			//把图片画到画布上
			img.onload=function(){
				ctx.drawImage(img,57,0,57,64);
			}
			img1.onload=function(){
				ctx.drawImage(img1,114,0,57,64);
			}
			img2.onload=function(){
				ctx.drawImage(img2,171,0,57,64);
			}
			img3.onload=function(){
				ctx.drawImage(img3,228,0,57,64);
			}
			img4.onload=function(){
				ctx.drawImage(img4,285,0,57,64);
			}
			img5.onload=function(){
				ctx.drawImage(img5,342,0,57,64);
			}
ctx.drawImage(img5,342,0,57,64)里面的参数分别为,图片,x坐标,y坐标,图片宽度,图片高度

Rendering:

Now, I want to make the canvas The pictures I draw can be adapted to both PC and mobile terminals. Then, I have to reprocess these codes. Now I only need to change the code to draw the pictures on the canvas.

 //把图片画到画布上
        function getCurrentImg() {
            var docW = $(document.body).width(); //获取页面宽度
              if (docW == 640) {//640是PC端的宽度
                 img.onload = function () {
                    ctx.drawImage(img, 22, 58, 55, 66);
                }
                img1.onload = function () {
                    ctx.drawImage(img1, 77, 58, 55, 66);
                }
                img2.onload = function () {
                    ctx.drawImage(img2, 132, 58, 55, 66);
                }
                img3.onload = function () {
                    ctx.drawImage(img3, 187, 58, 55, 66);
                }
                img4.onload = function () {
                    ctx.drawImage(img4, 242, 58, 55, 66);
                }
                img5.onload = function () {
                    ctx.drawImage(img5, 297, 58, 55, 66);
                }
              } else if (docW < 640) {//移动端的时候
                     img.onload = function () {
                        ctx.drawImage(img, 19, 51, 40, 45);
                    }
                    img1.onload = function () {
                        ctx.drawImage(img1, 59, 51, 40, 45);
                    }
                    img2.onload = function () {
                        ctx.drawImage(img2, 99, 51, 40, 45);
                    }
                    img3.onload = function () {
                        ctx.drawImage(img3, 139, 51, 40, 45);
                    }
                    img4.onload = function () {
                        ctx.drawImage(img4, 179, 51, 40, 45);
                    }
                    img5.onload = function () {
                        ctx.drawImage(img5, 219, 51, 40, 45);
                    }
              }
        }
        getCurrentImg();
        $(window).resize(function () {//页面大小发生改变的时候自动刷新页面
            var docW = $(document.body).width();
            var canvas = document.getElementById("myCanvas");
             //var ctx = canvas.getContext(&#39;2d&#39;);
             if (docW == 640) {
                canvas.height=canvas.height;//页面改变时清除画布
                 ctx.drawImage(img, 22, 58, 55, 66);
                    ctx.drawImage(img1, 77, 58, 55, 66);
                    ctx.drawImage(img2, 132, 58, 55, 66);
                    ctx.drawImage(img3, 187, 58, 55, 66);
                    ctx.drawImage(img4, 242, 58, 55, 66);
                    ctx.drawImage(img5, 297, 58, 55, 66);
                      
             } else if (docW < 640) {
                 canvas.height=canvas.height;//页面改变时清除画布
                    ctx.drawImage(img, 19, 51, 40, 45);
                   ctx.drawImage(img1, 59, 51, 40, 45);
                    ctx.drawImage(img2, 99, 51, 40, 45);
                    ctx.drawImage(img3, 139, 51, 40, 45);
                    ctx.drawImage(img4, 179, 51, 40, 45);
                    ctx.drawImage(img5, 219, 51, 40, 45);
                      
            }
        })

The resize() method is certain I only found out about it after some exploration. If not, you have to manually refresh the page every time you switch between PC and mobile. Although the function can still be implemented, the user experience is not very good.

Be sure to note that when the page size changes, you must clear the canvas first, otherwise there will be canvas overlays of different page sizes

I just briefly distinguish between the mobile terminal and the PC terminal. If If it is adaptive on mobile devices with different screen sizes, more if(){}else{} judgments are needed.

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. For more related tutorials, please visit CSS3 Video Tutorial, Html5 Video Tutorial!

Related recommendations:

php public welfare training video tutorial

CSS3 online manual

div/css graphic tutorial

##HTML5 graphic tutorial

HTML5 online manual

html5 special effects code collection

The above is the detailed content of css3 implements drawing pictures onto canvas (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
The Lost CSS Tricks of Cohost.orgThe Lost CSS Tricks of Cohost.orgApr 25, 2025 am 09:51 AM

In this post, Blackle Mori shows you a few of the hacks found while trying to push the limits of Cohost’s HTML support. Use these if you dare, lest you too get labelled a CSS criminal.

Next Level CSS Styling for CursorsNext Level CSS Styling for CursorsApr 23, 2025 am 11:04 AM

Custom cursors with CSS are great, but we can take things to the next level with JavaScript. Using JavaScript, we can transition between cursor states, place dynamic text within the cursor, apply complex animations, and apply filters.

Worlds Collide: Keyframe Collision Detection Using Style QueriesWorlds Collide: Keyframe Collision Detection Using Style QueriesApr 23, 2025 am 10:42 AM

Interactive CSS animations with elements ricocheting off each other seem more plausible in 2025. While it’s unnecessary to implement Pong in CSS, the increasing flexibility and power of CSS reinforce Lee's suspicion that one day it will be a

Using CSS backdrop-filter for UI EffectsUsing CSS backdrop-filter for UI EffectsApr 23, 2025 am 10:20 AM

Tips and tricks on utilizing the CSS backdrop-filter property to style user interfaces. You’ll learn how to layer backdrop filters among multiple elements, and integrate them with other CSS graphical effects to create elaborate designs.

SMIL on?SMIL on?Apr 23, 2025 am 09:57 AM

Well, it turns out that SVG's built-in animation features were never deprecated as planned. Sure, CSS and JavaScript are more than capable of carrying the load, but it's good to know that SMIL is not dead in the water as previously

'Pretty' is in the eye of the beholder'Pretty' is in the eye of the beholderApr 23, 2025 am 09:40 AM

Yay, let's jump for text-wrap: pretty landing in Safari Technology Preview! But beware that it's different from how it works in Chromium browsers.

CSS-Tricks Chronicles XLIIICSS-Tricks Chronicles XLIIIApr 23, 2025 am 09:35 AM

This CSS-Tricks update highlights significant progress in the Almanac, recent podcast appearances, a new CSS counters guide, and the addition of several new authors contributing valuable content.

Tailwind's @apply Feature is Better Than it SoundsTailwind's @apply Feature is Better Than it SoundsApr 23, 2025 am 09:23 AM

Most of the time, people showcase Tailwind's @apply feature with one of Tailwind's single-property utilities (which changes a single CSS declaration). When showcased this way, @apply doesn't sound promising at all. So obvio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools