


Canvas off-screen technology and magnifying glass implementation code example
This article mainly introduces the relevant information about canvas off-screen technology and magnifying glass implementation code examples. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Using canvas In addition to implementing filters, you can also use off-screen technology magnifying glass function.
For the convenience of explanation, this article is divided into 2 application parts:
Realizing watermark and center scaling
Realizing magnifying glass
1. What is off-screen technology?
canvas learning and filter implementation introduced the drawImage
interface. In addition to drawing images, this interface can also: Draw a canvas
object to another canvas
object . This is off-screen technology.
2. Implement watermark and center scaling
In the code, there are two canvas tags. They are visible and invisible respectively. The Context object on the invisible canvas object is where we place the image watermark.
For more details, please see the code comments:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Learn Canvas</title> <style> canvas { display: block; margin: 0 auto; border: 1px solid #222; } input { display: block; margin: 20px auto; width: 800px } </style> </head> <body> <p id="app"> <canvas id="my-canvas"></canvas> <input type="range" value="1.0" min="0.5" max="3.0" step="0.1"> <canvas id="watermark-canvas" style="display: none;"></canvas> </p> <script type="text/javascript"> window.onload = function () { var canvas = document.querySelector("#my-canvas") var watermarkCanvas = document.querySelector("#watermark-canvas") var slider = document.querySelector("input") var scale = slider.value var ctx = canvas.getContext('2d') var watermarkCtx = watermarkCanvas.getContext("2d") /* 给第二个canvas获取的Context对象添加水印 */ watermarkCanvas.width = 300 watermarkCanvas.height = 100 watermarkCtx.font = "bold 20px Arial" watermarkCtx.lineWidth = "1" watermarkCtx.fillStyle = "rgba(255 , 255 , 255, 0.5)" watermarkCtx.fillText("=== yuanxin.me ===", 50, 50) /****************************************/ var img = new Image() img.src = "./img/photo.jpg" /* 加载图片后执行操作 */ img.onload = function () { canvas.width = img.width; canvas.height = img.height; drawImageByScale(canvas, ctx, img, scale, watermarkCanvas); // 监听input标签的mousemove事件 // 注意:mousemove实时监听值的变化,内存消耗较大 slider.onmousemove = function () { scale = slider.value drawImageByScale(canvas, ctx, img, scale, watermarkCanvas); } } /******************/ } /** * * @param {Object} canvas 画布对象 * @param {Object} ctx * @param {Object} img * @param {Number} scale 缩放比例 * @param {Object} watermark 水印对象 */ function drawImageByScale(canvas, ctx, img, scale, watermark) { // 图像按照比例进行缩放 var width = img.width * scale, height = img.height * scale // (dx, dy): 画布上绘制img的起始坐标 var dx = canvas.width / 2 - width / 2, dy = canvas.height / 2 - height / 2 ctx.clearRect(0, 0, canvas.width, canvas.height) // No1 清空画布 ctx.drawImage(img, dx, dy, width, height) // No2 重新绘制图像 if (watermark) { // No3 判断是否有水印: 有, 绘制水印 ctx.drawImage(watermark, canvas.width - watermark.width, canvas.height - watermark.height) } } </script> </body> </html>
The effect is as shown below:
Drag the slider and you can Zoom in and out of images. Then right click to save the image. The saved image will already have a watermark, as shown below:
3. Implement a magnifying glass
Based on the above center zoom, the magnifying glass owner needs to pay attention to the following two parts:
Refined processing of canvas mouse response events: slide in, slide out, click and release
Recalculate the off-screen coordinates (see the code comments for detailed formula calculation ideas)
Recalculate the mouse relative to the canvas label Coordinates (see code comments for detailed formula calculation ideas)
The code is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> canvas { display: block; margin: 0 auto; border: 1px solid #222; } </style> </head> <body> <canvas id="my-canvas"></canvas> <canvas id="off-canvas" style="display: none;"></canvas> <script> var isMouseDown = false, scale = 1.0 var canvas = document.querySelector("#my-canvas") var offCanvas = document.querySelector("#off-canvas") // 离屏 canvas var ctx = canvas.getContext("2d") var offCtx = offCanvas.getContext("2d") // 离屏 canvas 的 Context对象 var img = new Image() window.onload = function () { img.src = "./img/photo.jpg" img.onload = function () { canvas.width = img.width canvas.height = img.height offCanvas.width = img.width offCanvas.height = img.height // 计算缩放比例 scale = offCanvas.width / canvas.width // 初识状态下, 两个canvas均绘制Image ctx.drawImage(img, 0, 0, canvas.width, canvas.height) offCtx.drawImage(img, 0, 0, canvas.width, canvas.height) } // 鼠标按下 canvas.onmousedown = function (event) { event.preventDefault() // 禁用默认事件 var point = windowToCanvas(event.clientX, event.clientY) // 获取鼠标相对于 canvas 标签的坐标 isMouseDown = true drawCanvasWithMagnifier(true, point) // 绘制在离屏canvas上绘制放大后的图像 } // 鼠标移动 canvas.onmousemove = function (event) { event.preventDefault() // 禁用默认事件 if (isMouseDown === true) { var point = windowToCanvas(event.clientX, event.clientY) drawCanvasWithMagnifier(true, point) } } // 鼠标松开 canvas.onmouseup = function (event) { event.preventDefault() // 禁用默认事件 isMouseDown = false drawCanvasWithMagnifier(false) // 不绘制离屏放大镜 } // 鼠标移出canvas标签 canvas.onmouseout = function (event) { event.preventDefault() // 禁用默认事件 isMouseDown = false drawCanvasWithMagnifier(false) // 不绘制离屏放大镜 } } /** * 返回鼠标相对于canvas左上角的坐标 * @param {Number} x 鼠标的屏幕坐标x * @param {Number} y 鼠标的屏幕坐标y */ function windowToCanvas(x, y) { var bbox = canvas.getBoundingClientRect() // bbox中存储的是canvas相对于屏幕的坐标 return { x: x - bbox.x, y: y - bbox.y } } function drawCanvasWithMagnifier(isShow, point) { ctx.clearRect(0, 0, canvas.width, canvas.height) // 清空画布 ctx.drawImage(img, 0, 0, canvas.width, canvas.height) // 在画布上绘制图像 /* 利用离屏,绘制放大镜 */ if (isShow) { var { x, y } = point var mr = 50 // 正方形放大镜边长 // (sx, sy): 待放大图像的开始坐标 var sx = x - mr / 2, sy = y - mr / 2 // (dx, dy): 已放大图像的开始坐标 var dx = x - mr, dy = y - mr // 将offCanvas上的(sx,sy)开始的长宽均为mr的正方形区域 // 放大到 // canvas上的(dx,dy)开始的长宽均为 2 * mr 的正方形可视区域 // 由此实现放大效果 ctx.drawImage(offCanvas, sx, sy, mr, mr, dx, dy, 2 * mr, 2 * mr) } /*********************/ } </script> </body> </html>
The magnifying glass effect is as shown below (the area marked by the red pen is our Square magnifying glass):
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 Html5 Video Tutorial!
Related recommendations:
php public welfare training video tutorial
The above is the detailed content of Canvas off-screen technology and magnifying glass implementation code example. For more information, please follow other related articles on the PHP Chinese website!

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

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.

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.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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