js笔记2

这篇文章介绍了如何使用WebAPI进行DOM操作,包括创建、移动和删除节点。同时,它讲解了HTTP的基本方法如GET、POST、PUT和DELETE,并对比了fetch和XHR在数据请求中的用法。此外,还涉及到了HTML5画布的使用,如绘制路径、圆和文本,以及如何加载和显示图像。
摘要由CSDN通过智能技术生成

API

Web API 接口参考 | MDN (mozilla.org)

基本DOM的操作

<!DOCTYPE html>
<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple DOM example</title>
  </head>
  <body>
      <section>
        <img src="dinosaur.png" alt="A red Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth.">
        <p>Here we will add a link to the <a href="https://www.mozilla.org/">Mozilla homepage</a></p>
      </section>
  </body>
  <script>
    //创建并放置新的节点
    var sect = document.querySelector('section');
    var para = document.createElement('p');
    para.textContent = "hello";
    sect.appendChild(para);
    //创造文本节点
    var text = document.createTextNode('-the premer source for web_dev knowledge');
    var linkpara = document.querySelector('p');
    linkpara.appendChild(text);

    //移动节点——放到底部
    sect.appendChild(linkpara);
    //删除节点——要删除的节点和其父节点
    linkpara.parentNode.removeChild(linkpara);
  </script>
</html>

HTTP方法

  • GET 请求指定的资源,获取数据
  • POST 发送数据给服务器(连续调用同一个 POST 可能会带来额外的影响)(一个 POST 请求通常是通过 HTML 表单发送,并返回服务器的修改结果。)
  • PUT 使用请求中的负载创建或者替换目标资源
  • DELETE 删除指定的资源

fetch 与 XHR

Example 1:
 function updateDisplay(verse) {
            verse = verse.replace(" ", "");
            verse = verse.toLowerCase();
            let url = verse + '.txt'; 
//使用 XMLHttpRequest() 的构造函数创建一个新的请求对象
            let request = new XMLHttpRequest();

            //XMLHttpRequest.open(method, url)
            //method要使用的 HTTP 方法,比如 GET、POST、PUT、DELETE、等。对于非 HTTP(S) URL 被忽略。
            request.open('GET', url);
            //设置我们期待的响应类型 — ---XHR 默认返回文本 
            request.responseType = 'text';
            //从网络获取资源是一个 asynchronous "异步" 操作,这意味着您必须等待该操作完成(例如,资源从网络返回),然后才能对该响应执行任何操作,否则会出错
            //XHR 允许你使用它的 onload 事件处理器来处理这个事件——当 load 事件触发时(当响应已经返回时)这个事件会被运行。
            request.onload = function () {
                poemDisplay.textContent = request.response;
            };
            request.send();
 }

fetch

 function updateDisplay(verse) {
            verse = verse.replace(" ", "");
            verse = verse.toLowerCase();
            let url = verse + '.txt';
     
		   fetch(url).then(function (response) {
                response.text().then(function (text) {
                    poemDisplay.textContent = text;
                });
            });
   }

向指定的url传输,得到返回后,进行function。传递回来的参数命名为response,将其转化为text格式。接着将其作为参数传到下一个function中。

Example 2:
fetch('products.json').then(function(response) {
  if(response.ok) {
    response.json().then(function(json) {
      products = json;
      initialize();
    });
  } else {
    console.log('Network request for products.json failed with response ' + response.status + ': ' + response.statusText);
  }
});

传回转化为json格式

Example 3:
fetch(url).then(function(response) {
  if(response.ok) {
    response.blob().then(function(blob) {
      objectURL = URL.createObjectURL(blob);
      showProduct(objectURL, product);
    });
  } else {
    console.log('Network request for "' + product.name + '" image failed with response ' + response.status + ': ' + response.statusText);
  }
});

画图

画布左上角的坐标是 (0, 0),横坐标(x)轴向右延伸,纵坐标(y)轴向下延伸。

img

获取画布上下文canvas context

var ctx = canvas.getContext('2d');

原点

translate()可用于移动画布的原点。

画布背景

填充色 即背景色

ctx.fillStyle = 'rgb(0, 0, 0)';

绘制一个覆盖整个区域的矩形(前两个参数是矩形左上顶点的坐标,后两个参数是矩形的长宽

ctx.fillRect(0, 0, width, height);

描边stroke和线条宽度

​ 使用 strokeStyle 属性来设置描边颜色

​ 使用 lineWidth 属性的值来修改描边宽度 (必须放在两行代码中间才有效 !)

​ 使用 strokeRect 来绘制一个矩形的轮廓。

ctx.strokeStyle = 'rgb(255, 255, 255)';
ctx.lineWidth = 5;
ctx.strokeRect(25, 25, 175, 200);

绘制路径
  • beginPath():在笔当前所在位置开始绘制一条路径。在新的画布中,笔起始位置为 (0, 0)。
  • moveTo():将笔移动至另一个坐标点,不记录、不留痕迹,只将笔“跳”至新位置。
  • fill():通过为当前所绘制路径的区域填充颜色来绘制一个新的填充形状。
  • stroke():通过为当前绘制路径的区域描边,来绘制一个只有边框的形状。
  • 路径也可和矩形一样使用 lineWidthfillStyle / strokeStyle 等功能。
//角度值转化为弧度值
function degToRad(degrees) {
    return degrees * Math.PI / 180;
  };

ctx.fillStyle = 'rgb(255, 0, 0)';
ctx.beginPath();
ctx.moveTo(50, 50);
// 绘制路径 画线
ctx.lineTo(150, 50);
var triHeight = 50 * Math.tan(degToRad(60));
ctx.lineTo(100, 50+triHeight);
ctx.lineTo(50, 50);
ctx.fill();

img

画圆

arc()函数有六个参数。前两个指定圆心的位置坐标,第三个是圆的半径,第四、五个是绘制弧的起、止角度(给定 0° 和 360° 便能绘制一个完整的圆),第六个是绘制方向(false 是顺时针,true 是逆时针)。

ctx.fillStyle = 'rgb(0, 0, 255)';
ctx.beginPath();
ctx.arc(150, 106, 50, degToRad(0), degToRad(360), false);
ctx.fill();
ctx.fillStyle = 'yellow';
ctx.beginPath();
ctx.arc(200, 106, 50, degToRad(-45), degToRad(45), true);
ctx.lineTo(200, 106);
ctx.fill();
文本

这两个函数有三个基本的参数:需要绘制的文字、文本框(顾名思义,围绕着需要绘制文字的方框)左上顶点的 X、Y 坐标。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0IHTWhW4-1673675374982)(C:\Users\XiaoXiaoli\AppData\Roaming\Typora\typora-user-images\image-20230114125944861.png)]

ctx.strokeStyle = 'white';
ctx.lineWidth = 1;
ctx.font = '36px arial';
ctx.strokeText('Canvas text', 50, 50);

ctx.fillStyle = 'red';
ctx.font = '48px georgia';
ctx.fillText('Canvas text', 50, 150);
图片

drawImage() 函数来嵌入图片

var image = new Image();
image.src = 'firefox.png';
image.onload = function() {
  ctx.drawImage(image, 50, 50);
}

img

图中包含六个精灵,它们组成了一趟完整的行走序列。每个精灵的尺寸为 102 × 148 像素。

ctx.drawImage(image, (sprite*102), 0, 102, 148, 0+posX, -74, 102, 148);
  • image 指定需要嵌入的图片。
  • 参数 2、3 指定切片左上顶点在原图的位置坐标,X 值为 sprite(精灵序列 0 - 5)乘 102,Y 值恒为 0。
  • 参数 4、5 指定切片尺寸:102 × 148 像素。
  • 参数 6、7 指定切片在画布绘制区域的坐上顶点坐标。X 坐标位置为 0 + posX,意味着我们可以通过修改 posX 的值来修改绘制的位置。
  • 参数 8、9 指定图片在画布中的尺寸。这里需要图片保持原始尺寸,因此我们指定宽、高值为 102、148。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值