搜尋
首頁web前端前端問答html5怎麼實現放大鏡功能

html5怎麼實現放大鏡功能

Jan 28, 2023 am 11:00 AM
html5放大鏡

html5實作放大鏡功能的方法:1、建立一個HTML範例檔案;2、使用html5 canvas標籤初始化圖片;3、取得canvas和image物件;4、透過「function drawAnchor() {... }」等方法將選取的區域放大,然後再繪製到原先的圖片上,確保兩塊區域的中心點一致即可。

html5怎麼實現放大鏡功能

本教學操作環境:Windows10系統、HTML5版、DELL G3電腦

html5怎麼實作放大鏡功能?

【HTML5】Canvas 實現放大鏡效果

#圖片放大鏡

##效果



##原理

首先選擇圖片的一塊區域,然後將這塊區域放大,然後再繪製到原先的圖片上,保證兩塊區域的中心點一致, 如下圖所示:

初始化

<canvas id="canvas" width="500" height="500">
</canvas>

<img  src="/static/imghwm/default1.png"  data-src="image.png"  class="lazy"     style="max-width:90%" id="img" alt="html5怎麼實現放大鏡功能" >

取得canvas 和image 對象,這裡使用 <img class="has lazy" src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/020/10ba557de489f1d72dd7ca06e186a8e6-2.png?x-oss-process=image/resize,p_40" alt="html5怎麼實現放大鏡功能" > 標籤預先載入圖片r​​rreee設定相關變數<pre class="brush:php;toolbar:false">var canvas = document.getElementById(&quot;canvas&quot;); var context = canvas.getContext(&quot;2d&quot;); var img = document.getElementById(&quot;img&quot;);</pre>畫背景圖片r​​rreee計算圖片被放大的區域的範圍這裡我們使用滑鼠的位置作為被放大區域的中心點(放大鏡隨著滑鼠移動而移動),因為canvas 在畫圖片的時候,需要知道左上角的座標以及區域的寬高,所以這裡我們計算區域的範圍<pre class="brush:php;toolbar:false">// 图片被放大区域的中心点,也是放大镜的中心点 var centerPoint = {}; // 图片被放大区域的半径 var originalRadius = 100; // 图片被放大区域 var originalRectangle = {}; // 放大倍数 var scale = 2; // 放大后区域 var scaleGlassRectangle</pre>繪製放大鏡區域裁切區域

放大鏡通常是圓形的,這裡我們使用 

clip

 函數裁切出一個圓形區域,然後在該區域中繪製放大後的圖。一旦裁減了某個區域,以後所有的繪圖都會被限制的這個區域裡,這裡我們使用 

save

 和 

restore

 方法清除裁切區域的影響。 save 保存目前畫布的一次狀態,包含 canvas 的上下文屬性,例如 

style

lineWidth

 等,然後會將這個狀態壓入一個堆疊。 restore 用來恢復上一次 save 的狀態,從堆疊中彈出最頂層的狀態。

function drawBackGround() {
    context.drawImage(img, 0, 0);
}

計算放大鏡區域

透過中心點、被放大區域的寬高以及放大倍率,獲得區域的左上角座標以及區域的寬高。

function calOriginalRectangle(point) {
    originalRectangle.x = point.x - originalRadius;
    originalRectangle.y = point.y - originalRadius;
    originalRectangle.width = originalRadius * 2;
    originalRectangle.height = originalRadius * 2;
}

繪製圖片

在這裡我們使用 context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height); 方法,將canvas 本身作為一副圖片,然後取被放大區域的影像,將其繪製到放大鏡區域裡。

context.save();
context.beginPath();
context.arc(centerPoint.x, centerPoint.y, originalRadius, 0, Math.PI * 2, false);
context.clip();
......
context.restore();

繪製放大邊緣

createRadialGradient

 用來繪製漸層影像

scaleGlassRectangle = {
    x: centerPoint.x - originalRectangle.width * scale / 2,
    y: centerPoint.y - originalRectangle.height * scale / 2,
    width: originalRectangle.width * scale,
    height: originalRectangle.height * scale
}

新增滑鼠事件#為canvas 新增滑鼠移動事件<pre class="brush:php;toolbar:false">context.drawImage(canvas,     originalRectangle.x, originalRectangle.y,     originalRectangle.width, originalRectangle.height,     scaleGlassRectangle.x, scaleGlassRectangle.y,     scaleGlassRectangle.width, scaleGlassRectangle.height );</pre>轉換座標
滑鼠事件取得座標一般為螢幕的或window 的座標,我們需要將其裝換為canvas 的座標。

getBoundingClientRect

 用來取得頁面中某個元素的左,上,右和下分別相對瀏覽器視窗的位置。

context.beginPath();
var gradient = context.createRadialGradient(
    centerPoint.x, centerPoint.y, originalRadius - 5,
    centerPoint.x, centerPoint.y, originalRadius);
gradient.addColorStop(0, &#39;rgba(0,0,0,0.2)&#39;);
gradient.addColorStop(0.80, &#39;silver&#39;);
gradient.addColorStop(0.90, &#39;silver&#39;);
gradient.addColorStop(1.0, &#39;rgba(150,150,150,0.9)&#39;);

context.strokeStyle = gradient;
context.lineWidth = 5;
context.arc(centerPoint.x, centerPoint.y, originalRadius, 0, Math.PI * 2, false);
context.stroke();
修改滑鼠樣式

我們可以透過css 來修改滑鼠樣式

canvas.onmousemove = function (e) {
    ......
}

圖表放大鏡
我們可能基於canvas 繪製一些圖表或圖像,如果兩個元素的座標離得比較近,就會為元素的選擇帶來一些影響,例如我們畫兩條線,一條線的座標是

(200.5, 400) -> (200.5, 200)

,另一行的座標為 
(201.5, 400) -> (201.5, 20),那麼這兩條線幾乎就會重疊在一起,如下圖所示:

# ########使用圖表放大鏡的效果############原理#######類似地圖中的圖例,放大鏡使用較為精確的圖例,如下圖所示:############在放大鏡座標系統中,原始的區域會變大,如下圖所示#########

绘制原始线段

首先创建一个线段对象

function Line(xStart, yStart, xEnd, yEnd, index, color) {
    // 起点x坐标
    this.xStart = xStart;
    // 起点y坐标
    this.yStart = yStart;
    // 终点x坐标
    this.xEnd = xEnd;
    // 终点y坐标
    this.yEnd = yEnd;
    // 用来标记是哪条线段
    this.index = index;
    // 线段颜色
    this.color = color;
}

初始化线段

// 原始线段
var chartLines = new Array();
// 处于放大镜中的原始线段
var glassLines;
// 放大后的线段
var scaleGlassLines;
// 位于放大镜中的线段数量
var glassLineSize;

function initLines() {

    var line;
    line = new Line(200.5, 400, 200.5, 200, 0, "#888");
    chartLines.push(line);
    line = new Line(201.5, 400, 201.5, 20, 1, "#888");
    chartLines.push(line);


    glassLineSize = chartLines.length;
    glassLines = new Array(glassLineSize);
    for (var i = 0; i < glassLineSize; i++) {
        line = new Line(0, 0, 0, 0, i);
        glassLines[i] = line;
    }

    scaleGlassLines = new Array(glassLineSize);
    for (var i = 0; i < glassLineSize; i++) {
        line = new Line(0, 0, 0, 0, i);
        scaleGlassLines[i] = line;
    }
}

绘制线段

function drawLines() {
    var line;
    context.lineWidth = 1;

    for (var i = 0; i < chartLines.length; i++) {
        line = chartLines[i];
        context.beginPath();
        context.strokeStyle = line.color;
        context.moveTo(line.xStart, line.yStart);
        context.lineTo(line.xEnd, line.yEnd);
        context.stroke();
    }
}

计算原始区域和放大镜区域

function calGlassRectangle(point) {
    originalRectangle.x = point.x - originalRadius;
    originalRectangle.y = point.y - originalRadius;
    originalRectangle.width = originalRadius * 2;
    originalRectangle.height = originalRadius * 2;

    scaleGlassRectangle.width = originalRectangle.width * scale;
    scaleGlassRectangle.height = originalRectangle.height * scale;
    scaleGlassRectangle.x = originalRectangle.x + originalRectangle.width / 2 - scaleGlassRectangle.width / 2;
    scaleGlassRectangle.y = originalRectangle.y + originalRectangle.height / 2 - scaleGlassRectangle.height / 2;

    // 将值装换为整数
    scaleGlassRectangle.width = parseInt(scaleGlassRectangle.width);
    scaleGlassRectangle.height = parseInt(scaleGlassRectangle.height);
    scaleGlassRectangle.x = parseInt(scaleGlassRectangle.x);
    scaleGlassRectangle.y = parseInt(scaleGlassRectangle.y);
}

计算线段在新坐标系统的位置

由原理图我们知道,放大镜中使用坐标系的图例要比原始坐标系更加精确,比如原始坐标系使用 1:100,那么放大镜坐标系使用 1:10,因此我们需要重新计算线段在放大镜坐标系中的位置。同时为了简便,我们将线段的原始坐标进行了转化,减去原始区域起始的x值和y值,即将原始区域左上角的点看做为(0,0)

function calScaleLines() {
    var xStart = originalRectangle.x;
    var xEnd = originalRectangle.x + originalRectangle.width;
    var yStart = originalRectangle.y;
    var yEnd = originalRectangle.y + originalRectangle.height;
    var line, gLine, sgLine;
    var glassLineIndex = 0;
    for (var i = 0; i < chartLines.length; i++) {
        line = chartLines[i];

        // 判断线段是否在放大镜中
        if (line.xStart < xStart || line.xEnd > xEnd) {
            continue;
        }
        if (line.yEnd > yEnd || line.yStart < yStart) {
            continue;
        }

        gLine = glassLines[glassLineIndex];
        sgLine = scaleGlassLines[glassLineIndex];
        if (line.yEnd > yEnd) {
            gLine.yEnd = yEnd;
        }
        if (line.yStart < yStart) {
            gLine.yStart = yStart;
        }

        gLine.xStart = line.xStart - xStart;
        gLine.yStart = line.yStart - yStart;
        gLine.xEnd = line.xEnd - xStart;
        gLine.yEnd = line.yEnd - yStart;

        sgLine.xStart = parseInt(gLine.xStart * scale);
        sgLine.yStart = parseInt(gLine.yStart * scale);
        sgLine.xEnd = parseInt(gLine.xEnd * scale);
        sgLine.yEnd = parseInt(gLine.yEnd * scale);
        sgLine.color = line.color;
        glassLineIndex++;
    }
    glassLineSize = glassLineIndex;
}

绘制放大镜中心点

绘制放大镜中心的瞄准器

function drawAnchor() {
    context.beginPath();
    context.lineWidth = 2;
    context.fillStyle = "#fff";
    context.strokeStyle = "#000";
    context.arc(parseInt(centerPoint.x), parseInt(centerPoint.y), 10, 0, Math.PI * 2, false);

    var radius = 15;
    context.moveTo(parseInt(centerPoint.x - radius), parseInt(centerPoint.y));
    context.lineTo(parseInt(centerPoint.x + radius), parseInt(centerPoint.y));
    context.moveTo(parseInt(centerPoint.x), parseInt(centerPoint.y - radius));
    context.lineTo(parseInt(centerPoint.x), parseInt(centerPoint.y + radius));
    //context.fill();
    context.stroke();
}

绘制放大镜

function drawMagnifyingGlass() {

    calScaleLines();

    context.save();
    context.beginPath();
    context.arc(centerPoint.x, centerPoint.y, originalRadius, 0, Math.PI * 2, false);
    context.clip();

    context.beginPath();
    context.fillStyle = "#fff";
    context.arc(centerPoint.x, centerPoint.y, originalRadius, 0, Math.PI * 2, false);
    context.fill();

    context.lineWidth = 4;
    for (var i = 0; i < glassLineSize; i++) {
        context.beginPath();
        context.strokeStyle = scaleGlassLines[i].color;
        context.moveTo(scaleGlassRectangle.x + scaleGlassLines[i].xStart, scaleGlassRectangle.y + scaleGlassLines[i].yStart);
        context.lineTo(scaleGlassRectangle.x + scaleGlassLines[i].xEnd, scaleGlassRectangle.y + scaleGlassLines[i].yEnd);
        context.stroke();
    }
    context.restore();

    context.beginPath();
    var gradient = context.createRadialGradient(
        parseInt(centerPoint.x), parseInt(centerPoint.y), originalRadius - 5,
        parseInt(centerPoint.x), parseInt(centerPoint.y), originalRadius);

    gradient.addColorStop(0.50, &#39;silver&#39;);
    gradient.addColorStop(0.90, &#39;silver&#39;);
    gradient.addColorStop(1, &#39;black&#39;);
    context.strokeStyle = gradient;
    context.lineWidth = 5;
    context.arc(parseInt(centerPoint.x), parseInt(centerPoint.y), originalRadius, 0, Math.PI * 2, false);
    context.stroke();

    drawAnchor();
}

添加事件

鼠标拖动

鼠标移动到放大镜上,然后按下鼠标左键,可以拖动放大镜,不按鼠标左键或者不在放大镜区域都不可以拖动放大镜。
为了实现上面的效果,我们要实现3种事件 mousedownmousemove, 'mouseup', 当鼠标按下时,检测是否在放大镜区域,如果在,设置放大镜可以移动。鼠标移动时更新放大镜中兴点的坐标。鼠标松开时,设置放大镜不可以被移动。

canvas.onmousedown = function (e) {
    var point = windowToCanvas(e.clientX, e.clientY);
    var x1, x2, y1, y2, dis;

    x1 = point.x;
    y1 = point.y;
    x2 = centerPoint.x;
    y2 = centerPoint.y;
    dis = Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2);
    if (dis < Math.pow(originalRadius, 2)) {
        lastPoint.x = point.x;
        lastPoint.y = point.y;
        moveGlass = true;
    }
}

canvas.onmousemove = function (e) {
    if (moveGlass) {
        var xDis, yDis;
        var point = windowToCanvas(e.clientX, e.clientY);
        xDis = point.x - lastPoint.x;
        yDis = point.y - lastPoint.y;
        centerPoint.x += xDis;
        centerPoint.y += yDis;
        lastPoint.x = point.x;
        lastPoint.y = point.y;
        draw();
    }
}

canvas.onmouseup = function (e) {
    moveGlass = false;
}

鼠标双击

当移动到对应的线段上时,鼠标双击可以选择该线段,将该线段的颜色变为红色。

canvas.ondblclick = function (e) {
    var xStart, xEnd, yStart, yEnd;
    var clickPoint = {};
    clickPoint.x = scaleGlassRectangle.x + scaleGlassRectangle.width / 2;
    clickPoint.y = scaleGlassRectangle.y + scaleGlassRectangle.height / 2;
    var index = -1;

    for (var i = 0; i < scaleGlassLines.length; i++) {
        var scaleLine = scaleGlassLines[i];

        xStart = scaleGlassRectangle.x + scaleLine.xStart - 3;
        xEnd = scaleGlassRectangle.x + scaleLine.xStart + 3;
        yStart = scaleGlassRectangle.y + scaleLine.yStart;
        yEnd = scaleGlassRectangle.y + scaleLine.yEnd;

        if (clickPoint.x > xStart && clickPoint.x < xEnd && clickPoint.y < yStart && clickPoint.y > yEnd) {
            scaleLine.color = "#f00";
            index = scaleLine.index;
            break;
        }
    }

    for (var i = 0; i < chartLines.length; i++) {
        var line = chartLines[i];
        if (line.index == index) {
            line.color = "#f00";
        } else {
            line.color = "#888";
        }
    }

    draw();
}

键盘事件

因为线段离得比较近,所以使用鼠标移动很难精确的选中线段,这里使用键盘的wasd 来进行精确移动

document.onkeyup = function (e) {
    if (e.key == &#39;w&#39;) {
        centerPoint.y = intAdd(centerPoint.y, -0.2);
    }
    if (e.key == &#39;a&#39;) {
        centerPoint.x = intAdd(centerPoint.x, -0.2);
    }
    if (e.key == &#39;s&#39;) {
        centerPoint.y = intAdd(centerPoint.y, 0.2);
    }
    if (e.key == &#39;d&#39;) {
        centerPoint.x = intAdd(centerPoint.x, 0.2);
    }
    draw();
}
推荐学习:《HTML5视频教程》  

以上是html5怎麼實現放大鏡功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
了解usestate():綜合反應國家管理指南了解usestate():綜合反應國家管理指南Apr 25, 2025 am 12:21 AM

useState()isaReacthookusedtomanagestateinfunctionalcomponents.1)Itinitializesandupdatesstate,2)shouldbecalledatthetoplevelofcomponents,3)canleadto'stalestate'ifnotusedcorrectly,and4)performancecanbeoptimizedusinguseCallbackandproperstateupdates.

使用React的優點是什麼?使用React的優點是什麼?Apr 25, 2025 am 12:16 AM

ReactispupularduetoItsOmpontement,基於虛擬,虛擬詞,Richecosystem和declarativedation.1)基於組件的harchitectureallowslowsforreusableuipieces。

在React中調試:識別和解決共同問題在React中調試:識別和解決共同問題Apr 25, 2025 am 12:09 AM

todebugreactapplicationsefectefectionfection,usethestertate:1)proppropdrillingwithcontextapiorredux.2)使用babortControllerToptopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRollerTopRaceeDitions.3)intleleassynChronOusOperations.3)

反應中的usestate()是什麼?反應中的usestate()是什麼?Apr 25, 2025 am 12:08 AM

usestate()inrectallowsStateMagementionInfunctionalComponents.1)ITSIMPLIFIESSTATEMAGEMENT,MACHECODEMORECONCONCISE.2)usetheprevcountfunctionToupdateStateBasedonitspReviousViousViousvalue,deveingingStaleStateissues.3)

usestate()與用戶ducer():為您的狀態需求選擇正確的掛鉤usestate()與用戶ducer():為您的狀態需求選擇正確的掛鉤Apr 24, 2025 pm 05:13 PM

selectUsestate()forsimple,獨立的variables; useusereducer()forcomplexstateLogicorWhenStatedIppedsonPreviousState.1)usestate()isidealForsImpleupDatesLikeToggGlikGlingaBglingAboolAboolAupDatingacount.2

使用usestate()管理狀態:實用教程使用usestate()管理狀態:實用教程Apr 24, 2025 pm 05:05 PM

useState優於類組件和其它狀態管理方案,因為它簡化了狀態管理,使代碼更清晰、更易讀,並與React的聲明性本質一致。 1)useState允許在函數組件中直接聲明狀態變量,2)它通過鉤子機制在重新渲染間記住狀態,3)使用useState可以利用React的優化如備忘錄化,提升性能,4)但需注意只能在組件頂層或自定義鉤子中調用,避免在循環、條件或嵌套函數中使用。

何時使用usestate()以及何時考慮替代狀態管理解決方案何時使用usestate()以及何時考慮替代狀態管理解決方案Apr 24, 2025 pm 04:49 PM

useUsestate()forlocalComponentStateMangementighatighation; 1)usestate()isidealforsimple,localforsimple.2)useglobalstate.2)useglobalstateSolutionsLikErcontExtforsharedState.3)

React的可重複使用的組件:增強代碼可維護性和效率React的可重複使用的組件:增強代碼可維護性和效率Apr 24, 2025 pm 04:45 PM

ReusableComponentsInrectenHanceCodainainability and效率byallowingDevelostEsteSeTheseTheseThesAmeCompOntionActActRossDifferentPartSofanApplicationorprojects.1)heSredunceRedUndenceNandSimplifyUpdates.2)yensureconsistencyInuserexperience.3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境