search
HomeWeb Front-endH5 TutorialDetailed explanation of graphic code of Html5 Canvas Image (2)

The previous article mainly talked about the basic Image API provided by canvas;

In this article we use canvas Provided Image API and transformation to achieve some examples: simple movement of the car, simple gamesmap, image translation and zoom;

used in the following applications Picture:

##


##Our position on Canvas (50,50) How to display the first 1/8 part of the tanks (the first tank)? We use part of image api;

context.drawImage(tanks,0,0,32,32,50,50,32,32);

How to rotate the current tank 90 degrees?

The rotation operation in Canvas is the same whether it is for shape, text or image;

First of all, you need to Push the current state of the canvas onto the stack: context.save();

and then start the transformation: context.setTransform(1,0,0,1,0 ,0);

We need to rotate 90 degrees with the tank itself as the center, so we need to translate the origin to the center of the tank;

The position (x,y) of the tank is (50,50), and the size (w,h) is (32,32); so its center point is (x+w/2,y+h/2);

Translation origin: context.translate(50 + 16, 50 + 16);

Rotation: context.rotate(90*Math.PI /180);

Note: Originally, the picture was drawn at the (50,50) position of the canvas. After the origin is translated, the position coordinates become (-16,-16 );

Draw the picture: context.drawImage(tanks, 0, 0, 32, 32, -16, -16, 32, 32);

图片旋转---完整代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Images</title>
<script type="text/javascript" src="../script/modernizr-latest.js"></script>
<script type="text/javascript">
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded() {
canvasApp();
}

function canvasSupport() {
return Modernizr.canvas;
}

function canvasApp() {

if(!canvasSupport()) {
return;
}

var theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");

var tanks = new Image();
tanks.addEventListener(&#39;load&#39;, eventLoaded, false);
tanks.src = "tanks.png";
var x = 50;
var y = 50;

function eventLoaded() {
drawScreen();
}

function drawScreen() {
context.fillStyle = "#aaaaaa";
context.fillRect(0, 0, 500, 500);
context.save();
context.setTransform(1, 0, 0, 1, 0, 0)
context.translate(x + 16, y + 16);
var angleInRadians = 90 * Math.PI / 180;
context.rotate(angleInRadians);
context.drawImage(tanks, 0, 0, 32, 32, -16, -16, 32, 32);
context.restore();
}

}
</script>
</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvasOne" width="500" height="500">
Your browser does not support HTML5 Canvas.
</canvas>
</div>
</body>
</html>

Wheel rotation animation

##tanks There are 8 tanks in total, and the size of each image is (32,32);

What if we want to display the second tank at the position of (50,50)?

The 2nd one: context.drawImage(tanks, 32*(2-1), 0, 32, 32, -16, -16, 32, 32);

The 3rd one: context.drawImage(tanks, 32*(3-1), 0, 32, 32, -16, -16, 32, 32);

And so on, the 8th one: context.drawImage(tanks, 32*(8-1), 0, 32, 32, -16, -16, 32, 32);

The difference between each tank picture lies in its wheel position. If we use

Timer100ms to display these 1 to 8 tank pictures in turn, we will see a tank Wheel rotation animation;

tank轮子转动动画--完整代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Images</title>
<script type="text/javascript" src="../script/modernizr-latest.js"></script>
<script type="text/javascript">
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded() {
canvasApp();
}

function canvasSupport() {
return Modernizr.canvas;
}

function canvasApp() {

if(!canvasSupport()) {
return;
}

var theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");

var tanks = new Image();
tanks.addEventListener(&#39;load&#39;, eventLoaded, false);
tanks.src = "tanks.png";
//控制取第几个tank
var animationFrames = [0,1,2,3,4,5,6,7];
var frameIndex = 0;//当前动画帧
//tank的显示位置
var x = 50;
var y = 50;

function eventLoaded() {
startUp();
}

function drawScreen() {
context.fillStyle = "#aaaaaa";
context.fillRect(0, 0, 500, 500);
context.save();
context.setTransform(1, 0, 0, 1, 0, 0)
context.translate(x + 16, y + 16);
var angleInRadians = 90 * Math.PI / 180;
context.rotate(angleInRadians);
var sourceX = animationFrames[frameIndex] * 32;//每次取图片的X位置
context.drawImage(tanks, sourceX, 0, 32, 32, -16, -16, 32, 32);
context.restore();
frameIndex++;
//循环动画控制
if(frameIndex == animationFrames.length) {
frameIndex = 0;
}
}

//计时器
function startUp() {
setInterval(drawScreen, 100);
}
}
</script>
</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvasOne" width="500" height="500">
Your browser does not support HTML5 Canvas.
</canvas>
</div>
</body>
</html>

tank's

horizontal movement effect is easy to implement, just change each frame of animation each time, The x position of the display of the tank picture is OK; ! !

We define a 320*320 size Canvas and use image map to draw a simple game map;

There are four small pictures in the picture map, all of which are 32*32: main background, obstacles, top and bottom bricks, left and right bricks;

First, We divide the Canvas into 10*10 small grids, and the size of each small grid is 32*32, which is exactly the same size as the picture;

Then we define a

Two-dimensional array to store the index of the picture to be displayed in each small grid;

Then use a two-layer loop to draw the picture, and the map comes out;

Take a look at the renderings first:

##

简单的游戏地图--完整代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Images</title>
<script type="text/javascript" src="../script/modernizr-latest.js"></script>
<script type="text/javascript">
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded() {
canvasApp();
}

function canvasSupport() {
return Modernizr.canvas;
}

function canvasApp() {

if(!canvasSupport()) {
return;
}

var theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");

var tileSheet = new Image();

tileSheet.addEventListener(&#39;load&#39;, eventLoaded, false);
tileSheet.src = "map.png";
var mapRows = 10;
var mapCols = 10;
var Map = [
[3, 2, 2, 2, 0, 2, 2, 2, 2, 3], 
[0,0,0,0,0,0,0,0,0, 0], 
[3,0, 1,0, 1,0, 1,0,0, 3], 
[3, 1,0,0, 1,0,0, 1,0, 3], 
[3,0,0,0, 1, 1,0, 1,0, 3], 
[3,0,0, 1,0,0,0, 1,0, 3], 
[3,0,0,0,0,0,0, 1,0, 3], 
[0,0, 1,0, 1,0, 1,0,0, 0], 
[3,0,0,0,0,0,0,0,0, 3], 
[3, 2, 2, 2,0, 2, 2, 2, 2, 3]
];
function eventLoaded() {
drawScreen()
}

function drawScreen() {
for(var rowCtr = 0; rowCtr < mapRows; rowCtr++) {
for(var colCtr = 0; colCtr < mapCols; colCtr++) {
var cur = Map[rowCtr][colCtr];
var sourceX = cur * 32;
context.drawImage(tileSheet, sourceX, 0, 32, 32, colCtr * 32, rowCtr * 32, 32, 32);
}
}
}

}
</script>
</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvasOne" width="320" height="320">
Your browser does not support HTML5 Canvas.
</canvas>
</div>
</body>
</html>

Share another Image Api application:

图像的平移缩放

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Pan</title>
<script type="text/javascript" src="../script/modernizr-latest.js"></script>
<script type="text/javascript">
window.addEventListener("load", eventWindowLoaded, false);

function eventWindowLoaded() {
canvasApp();
}

function canvasSupport() {
return Modernizr.canvas;
}

function canvasApp() {

if(!canvasSupport()) {
return;
}

var theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");

var panImg = new Image();
panImg.addEventListener(&#39;load&#39;, eventPhotoLoaded, false);
panImg.src = "pan.jpg";

var windowWidth = 500;
var windowHeight = 500;
var windowX = 0;
var windowY = 0;
var currentScale = 1;
var minScale = .2
var maxScale = 3;
var scaleIncrement = 0.1;

function eventPhotoLoaded() {
startUp();
}

function drawScreen() {
context.fillStyle = "#ffffff";
context.fillRect(0, 0, 500, 500);
context.drawImage(panImg, windowX, windowY, windowWidth, windowHeight, 0, 0, windowWidth * currentScale, windowHeight * currentScale);
}

function startUp() {
setInterval(drawScreen, 100);
}


document.onkeydown = function(e) {
e = e ? e : window.event;
switch (e.keyCode) {
case 38:
//up
windowY -= 10;
if(windowY < 0) {
windowY = 0;
}
break;
case 40:
//down
windowY += 10;
if(windowY > photo.height - windowHeight) {
windowY = photo.height - windowHeight;
}
break;
case 37:
//left
windowX -= 10;
if(windowX < 0) {
windowX = 0;
}
break;
case 39:
//right
windowX += 10;
if(windowX > photo.width - windowWidth) {
windowX = photo.width - windowWidth;
}
break;
case 109:
//-
currentScale -= scaleIncrement;
if(currentScale < minScale) {
currentScale = minScale;
}
break;
case 107:
//+
currentScale += scaleIncrement;
if(currentScale > maxScale) {
currentScale = maxScale;
}
}
}
}
</script>
</head>
<body>
<div style="position: absolute; top: 50px; left: 50px; padding:5px solid #000000">
<canvas id="canvasOne" width="500" height="500">
Your browser does not support HTML5 Canvas.
</canvas>
</div>
</body>
</html>

该代码中,有一个图片"pan.jpg",大家随便找一个比较大的图就可以;

快运行,看看效果吧!

 

##Picture 1: tanks--[32*32]*8--tanks.png Picture 2: map--[32*32]*4--map.png

The above is the detailed content of Detailed explanation of graphic code of Html5 Canvas Image (2). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the H5 tag in HTML?What is the H5 tag in HTML?May 09, 2025 am 12:11 AM

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

H5 Code: A Beginner's Guide to Web StructureH5 Code: A Beginner's Guide to Web StructureMay 08, 2025 am 12:15 AM

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

H5 Code Structure: Organizing Content for ReadabilityH5 Code Structure: Organizing Content for ReadabilityMay 07, 2025 am 12:06 AM

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

H5 vs. HTML5: Clarifying the Terminology and RelationshipH5 vs. HTML5: Clarifying the Terminology and RelationshipMay 05, 2025 am 12:02 AM

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

HTML5 Features: The Core of H5HTML5 Features: The Core of H5May 04, 2025 am 12:05 AM

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

H5: Exploring the Latest Version of HTMLH5: Exploring the Latest Version of HTMLMay 03, 2025 am 12:14 AM

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

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

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.