当前位置:Gxlcms > JavaScript > js实现图片区域可点击大小随意改变(适用移动端)代码实例

js实现图片区域可点击大小随意改变(适用移动端)代码实例

时间:2021-07-01 10:21:17 帮助过:5人阅读

实现图片区域可点击,实际上使用map是可以的,但是适配效果并不好,图片只能是固定大小的值,而且点都被写死了。

在这里,我使用的js基于canvas写的一个小工具。可以圈出你需要点击的部分,然后生成一串json,在预览页面就可以看见效果了;

在实际应用中,只要用工具处理一下图片,再把数据存入数据库,就很方便了;

使用工具时,先上传图片。然后就可以圈了,圈完一定要记得,点击保存数据,,,接着就可以预览了,预览点击的效果,可以看控制台,

首先是工具

首先工具的html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
      *{
        padding: 0;
        margin: 0;
        font-family: "微软雅黑";
      }
      .hide{
        display: none;
      }
      canvas{
        border: 1px solid red;
        display: block;
        margin: 0 auto;
        background-position: 0 0;
        background-repeat: no-repeat;
        background-size: 100% 100%;
         
      }
      .cover{
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.4);
      }
      .cover p{
        text-align: center;
      }
      .btn{
        width: 800px;
        margin: 0 auto;
        padding-top: 10px;
      }
      .btn p{
        padding-bottom: 10px;
      }
      a{
        text-decoration: none;
        color: #000;
      }
      button{
        line-height: 30px;
        padding: 0 10px;
        cursor: pointer;
        border-radius: 4px;
        background: #449d44;
        color: #fff;
        border: none;
      }
    </style>
  </head>
  <body>
    <div class="btn">
      <p>
        <button onclick="saveData()">保存数据</button>
        <button onclick="getData()">导入数据</button>
        <button onclick="seeData(true)">查看数据</button>
        <a href="preview.html" rel="external nofollow" target="_blank"><button>预览效果</button></a>
      </p>
      <p>
        <input type="file" name="imgload" id="imgload" value="上传图片" />
      </p>
      <p>
        <button onclick="reduo()">撤销</button>
        <button onclick="clearAll()">清除</button>
      </p>
      <p>
        基础宽度:<input type="text" name="width" id="width" value="800" />
      </p>
      <p>
        基础高度:<input type="text" name="width" id="height" value="600" />
      </p>
    </div>
    <canvas id="canvas" width="800" height="600"></canvas>
    <div class="cover hide">
      <p>
        <span>url地址:</span>
        <input type="text" name="" id="urlAddress" value="" />
      </p>
      <p>
        <span>描述:</span>
        <input type="text" name="dec" id="dec" value="" />
      </p>
      <p>
        <button class="contain">确认</button>
      </p>
    </div>
  </body>
  <script type="text/javascript" src="js/jquery.js"></script>
  <script type="text/javascript" src="js/index.js"></script>
</html>

接着是工具的js代码

var canvas = document.getElementById('canvas');  
var ctx = canvas.getContext('2d');
ctx.lineWidth = 1;
ctx.strokeStyle="green";
/*ctx.beginPath();
ctx.moveTo(10, 100);
ctx.lineTo(300,100);
ctx.stroke(); 
ctx.closePath();*/
var run = false;
var moduleList = [];
var path = [];
var $baseImg = '';
 
var $cover = $(".cover");
var $urlAddress = $('#urlAddress');
var $dec = $("#dec");
 
var $baseWidth = $('#width');
var $baseHeight = $('#height');
 
 
canvas.onmousedown = function(e){
  //console.log(e.clientX);
  //console.log(e.offsetX); 
  ctx.beginPath();
  ctx.moveTo(e.offsetX, e.offsetY);
  path.push({
    x:e.offsetX,
    y:e.offsetY
  });
  run = true;
}
 
canvas.onmousemove = function(e){
  //var x = e.offsetX;    
  if(run){
    ctx.lineTo(e.offsetX, e.offsetY);
    ctx.stroke();
    path.push({
      x:e.offsetX,
      y:e.offsetY
    });
  }
}
canvas.onmouseup = function(e){
  run = false;
  ctx.closePath();
  if(path.length > 10){
    $cover.removeClass('hide');
  }else{
    path = []; 
  }
}
 
 
//保存数据
function saveData(){
  var data = {
    "dec":"图片点击",
    "version":"1",
    "img":$baseImg,
    "module":moduleList,
    "baseWidth":$baseWidth.val(),
    "baseHeight":$baseHeight.val()
  }
  console.log(JSON.stringify(data));
  localStorage.setItem("data",JSON.stringify(data));
}
//查看数据
function seeData(flag){
  var data = {
    "dec":"图片点击",
    "version":"1",
    "img":$baseImg,
    "module":moduleList,
    "baseWidth":$baseWidth.val(),
    "baseHeight":$baseHeight.val()
  }
  if(flag){
    console.log(JSON.stringify(data));
  }
  return data;
}
 
 
 
//图片背景
$('#imgload').on('change',function(){
    imgToBase64(this.files[0],function(result){
      console.log(result);
      var base64Data = 'url(' + result + ')';
      $(canvas).css({'background-image': base64Data});
      $baseImg = result;
    });
     
});
 
//转化为base64
function imgToBase64(file,callback){
   var reader = new FileReader();
 
  reader.onload = function (e) {
    callback(e.target.result);
  };
  reader.readAsDataURL(file); // 读取完后会调用onload方法
}
 
//确认信息
$cover.on('click','.contain',function(){
  if($urlAddress.val() == ''){
    alert('地址不能为空');
  }else{
    moduleList.push({
      id:getName(),
      path:path,
      url:$urlAddress.val(),
      dec:$dec.val()
    });
    path = []; 
    $cover.addClass('hide');
  }
});
 
 
//修改高度和宽度
$baseWidth.on('change',function(){
  $(canvas).css({'width': $(this).val()});
});
$baseHeight.on('change',function(){
  $(canvas).css({'height': $(this).val()});
});
 
 
//随机获取名称
function getName(){
  var timer = new Date();
  var arr = JSON.stringify(timer).replace(/:|-|"/g ,'').split('.');
  var str = arr.join('');
  return str;
}
 
 
//导入模板
function getData(){
  var data = JSON.parse(localStorage.getItem("data"));
  if(data){
    moduleList = data.module;;
    $baseImg = data.img;
    drawn(data);
  }else{
    alert('没有模板数据.');
  }
}
 
//撤销
function reduo(){
  moduleList.pop();
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawn(seeData());
}
 
 
//清除所有
function clearAll(){
  moduleList = [];
  ctx.clearRect(0, 0, canvas.width, canvas.height);
}
 
//给数据,画出来
function drawn(data){
  ctx.clearRect(0, 0, canvas.width, canvas.height);
    var module = data.module;
    var base64Data = 'url(' + data.img + ')';
    $(canvas).css({'background-image': base64Data});
    $baseWidth.val(data.baseWidth);
    $baseHeight.val(data.baseHeight);
    $(canvas).css({'width': data.baseWidth,'height':data.baseHeight});
     
    //开始画
    for(var i = 0; i < module.length;i++){ 
      var path = module[i].path;
      ctx.beginPath();
      ctx.moveTo(path[0].x, path[0].y);
      for(var j = 1; j < path.length; j++){
        ctx.lineTo(path[j].x, path[j].y);
        ctx.stroke(); 
      }
      ctx.closePath();  
    }
}

最后是preview.html预览

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <style type="text/css">
      *{
        padding: 0;
        margin: 0;
      }
      body,html{
        width: 100%;
        height: 100%;
      }
      canvas{
        background-position: 0 0;
        background-repeat: no-repeat;
        background-size: 100% 100%;
        width: 100%;
        height: 100%;
      }
      .wrap{
        border: 1px solid red;
        margin: 0 auto;
        width: 800px;
        height: 600px;
      }
    </style>
  </head>
  <body>
    <div class="wrap">
      <canvas id="canvas" ></canvas>
    </div>
     
  </body>
  <script type="text/javascript" src="js/jquery.js"></script>
  <script type="text/javascript">
   
    var $canvas = $('#canvas');
    var canvas = $canvas[0];  
     
    var data = JSON.parse(localStorage.getItem("data"));
    var ctx = canvas.getContext('2d');
      ctx.lineWidth = 1;
      ctx.strokeStyle="rgba(0,0,0,0)";
    var module = data.module;   
    var rateWidth = $canvas.width()/data.baseWidth;
    var rateHeight = $canvas.height()/data.baseHeight;
    var base64Data = 'url(' + data.img + ')';
    $canvas.css({'background-image': base64Data});
     
    console.log(rateWidth);
    console.log(rateHeight);
    //判断点击了图片的某个地方
    canvas.onclick = function(e){
       var x = event.pageX - canvas.getBoundingClientRect().left;
       var y = event.pageY - canvas.getBoundingClientRect().top;
      for(var i = 0; i < module.length;i++){ 
        var path = module[i].path;
        ctx.beginPath();
        ctx.moveTo(path[0].x*rateWidth, path[0].y*rateHeight);
        for(var j = 1; j < path.length; j++){
          ctx.lineTo(path[j].x*rateWidth, path[j].y*rateHeight); 
        }
        ctx.closePath();  
        if(ctx.isPointInPath(x, y)){
          clickCall(module[i]);
          return;
        }
      }
    };
     
    //点击中了选中的区域
    function clickCall(result){
      console.log(result.dec);
      console.log(result.url);      
    }
  </script>
</html>

效果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行