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
Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version